π§© Components & Templates
Deep dive into Angular components, lifecycle hooks, Inputs/Outputs, ViewChild, and content projection.
Anatomy of an Angular Component
Components are the main building blocks of Angular applications. Each component consists of a TypeScript class, an HTML template, and CSS styles.
user.component.ts
TypeScript
import { Component } from '@angular/core'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent { username: string = 'JohnDoe'; }
Component Lifecycle Hooks
Angular manages the lifecycle of components as they are created, updated, and destroyed. Implement lifecycle interfaces to respond to key lifecycle events.
| Hook | Purpose | Common Use Case |
|---|---|---|
| ngOnChanges | Executes before ngOnInit and when input properties change. | React to updated @Input() values. |
| ngOnInit | Called once after component initialization. | Fetch initial data from API services. |
| ngDoCheck | Called during every change detection run. | Custom change detection logic. |
| ngAfterViewInit | Called after component view & child views are initialized. | Access DOM or @ViewChild references. |
| ngOnDestroy | Called immediately before component destruction. | Unsubscribe Observables & clear timers. |
Component Communication (@Input and @Output)
Pass data into child components using `@Input()` and emit custom events to parent components using `@Output()` with `EventEmitter`.
child.component.ts
TypeScript
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: ` <p>Hello {{ name }}</p> <button (click)="notifyParent()">Click Me</button> ` }) export class ChildComponent { @Input() name!: string; @Output() action = new EventEmitter<string>(); notifyParent() { this.action.emit('Child button was clicked!'); } }
ViewChild and Content Projection
Use `@ViewChild` to query template elements or child component instances. Use `
card.component.ts
TypeScript
// Content projection container @Component({ selector: 'app-card', template: ` <div class="card"> <div class="card-header"><ng-content select="[header]"></ng-content></div> <div class="card-body"><ng-content></ng-content></div> </div> ` }) export class CardComponent {}