Basics
Components, templates & encapsulation
Components as the composition unit — inputs, outputs, projection and view encapsulation.
A component is a class annotated with @Component that owns a slice of the DOM. It exposes data down with @Input(), emits events up with @Output() (an EventEmitter), and composes with other components by selector — Angular favours composition over inheritance.
A component is a sealed appliance: inputs are the power socket, outputs are the status lights, and encapsulated styles are the casing that keeps its wiring from shorting the rest of the house.
Key concepts
1
Templates are compiled ahead of time (AOT) into optimised render instructions, so template type-checking (strictTemplates) catches binding errors at build time rather than at runtime.
AOTstrictTemplates
2
View encapsulation scopes styles to the component. The default Emulated mode rewrites selectors with generated attributes; ShadowDom uses the native shadow tree; None leaks styles globally — reach for it deliberately, not by accident.
View encapsulationEmulatedShadowDomNone
3
Pitfall: doing heavy work in the constructor. The constructor should only wire dependencies; DOM-dependent and input-dependent work belongs in lifecycle hooks. Best practice: keep components thin (presentation) and push logic into services, so components stay testable and reusable.
Pitfall:Best practice:
typescript
@Component({
selector: 'app-rating',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button *ngFor="let star of stars"
[class.filled]="star <= value"
(click)="select.emit(star)">★</button>
`,
})
export class RatingComponent {
@Input({ required: true }) value!: number;
@Input() max = 5;
@Output() select = new EventEmitter<number>();
get stars() { return Array.from({ length: this.max }, (_, i) => i + 1); }
}