Components in Angular
Estimated study time: 8 minutes. The fundamental building block of every Angular application.
A component controls a section of the screen — its template (HTML), its styling (CSS), and its behavior (TypeScript class) all bundled together. Every Angular UI is a tree of components.
Anatomy of a Component
import { Component } from '@angular/core';
@Component({
selector: 'app-product-card',
templateUrl: './product-card.component.html',
styleUrls: ['./product-card.component.css']
})
export class ProductCardComponent {
@Input() productName!: string;
@Input() price!: number;
addToCart() {
console.log(`${this.productName} added to cart`);
}
}
The Three Parts
- Decorator (@Component) — metadata telling Angular how to process the class: its selector, template, and styles.
- Template — the HTML that defines what's rendered, with Angular-specific syntax for binding and directives.
- Class — the TypeScript logic: properties, methods, and lifecycle hooks.
Using a Component
Once declared, a component is used like a custom HTML tag anywhere its module allows:
<app-product-card [productName]="'Wireless Mouse'" [price]="799"></app-product-card>
Standalone Components
Modern Angular versions support standalone components, which don't need to be declared inside an NgModule — reducing boilerplate for smaller or newer projects.
@Component({
selector: 'app-badge',
standalone: true,
imports: [CommonModule],
template: `<span class="badge">{{ label }}</span>`
})
export class BadgeComponent {
@Input() label = '';
}
💡 Tip: Keep components small and focused on one piece of UI — if a component's template and class are both growing large, it's usually a sign to split it into smaller child components.