Component Anatomy and Decorators
Everything a component is made of, and how the @Component decorator ties a class, a template, and styles together.
2 min read
Every piece of UI in an Angular app is a component: a TypeScript class describing behavior and data, paired with a template describing what to render. The @Component decorator is the glue between them.
The decorator
import { Component } from '@angular/core';
@Component({
selector: 'app-user-card',
templateUrl: './user-card.component.html',
styleUrl: './user-card.component.css',
})
export class UserCardComponent {
name = 'Ada Lovelace';
role = 'Engineer';
isOnline = true;
}A decorator is a function that attaches metadata to the class beneath it — it doesn't change what the class does, it tells Angular how to treat it. Without @Component, UserCardComponent would just be a plain class with three properties; Angular would have no idea it's meant to render anything.
selectoris the custom tag name other templates use to place this component:<app-user-card></app-user-card>.templateUrlpoints at the HTML file to render. For very small components you can inline it instead withtemplate: '...'.styleUrlpoints at a CSS file scoped to this component (more on that scoping in the next lesson).
The template reads from the class
<!-- user-card.component.html -->
<div class="card">
<h2>{{ name }}</h2>
<p>{{ role }}</p>
<span *ngIf="isOnline">● Online</span>
</div>Every value inside {{ }} in the template is looked up on the component class. There's no separate "state management" step for a simple case like this — the class's properties are the source of truth, and Angular keeps the rendered HTML in sync with them.
Class members aren't just data
A component class can hold methods too, and templates can call them directly:
export class UserCardComponent {
name = 'Ada Lovelace';
isOnline = true;
toggleStatus(): void {
this.isOnline = !this.isOnline;
}
}<button (click)="toggleStatus()">Toggle status</button>You'll meet the (click) syntax properly in the event binding lesson — for now, notice that the template can trigger behavior defined entirely in the class, keeping markup declarative and logic in one place.
One file, one responsibility
By convention, each component gets its own file (or trio of files: .ts, .html, .css), named after what it represents rather than what it looks like. A UserCardComponent should describe and render a user card — if it starts fetching data, formatting dates, and managing a modal, that's usually a sign it's doing too much and some of that logic belongs in a service or a child component instead.