Components & Metadata (@Component)
Components are the primary building blocks of an Angular application. They consist of a TypeScript class, an HTML template, and CSS stylesheets, linked together using the @Component decorator.
1 Decoupled MVC Architecture
The @Component decorator applies configurations to a class, turning it into a functional component:
- selector: Custom CSS selector targeting where this component will be rendered in the DOM (e.g.
<app-user></app-user>). - templateUrl / template: Links external HTML layouts or defines inline markup structures.
- styleUrls / styles: Links external stylesheets or defines inline CSS selectors local to this component.
2 Declaring a Component Class
Let's inspect a modern component written in TypeScript:
TypeScript — User Component
import { Component } from '@angular/core';
@Component({
selector: 'app-user-profile',
template: `
{{ username }}
Status: {{ status }}
`,
styles: [`
.profile-card { border: 1px solid #ddd; padding: 16px; border-radius: 8px; }
`]
})
export class UserProfileComponent {
username: string = 'Balaji Nayak';
status: string = 'Active';
}
3 Code Challenge
Challenge: Write a new component class called
HeaderComponent that defines a selector app-header, an inline template displaying a logo banner, and basic component styling.