Components
A component is a template, some state, and the logic that ties them together. Everything you build in Angular is a tree of them, so the conventions in this chapter compound.
Anatomy
@Component({
selector: 'app-order-card', // how it is used in a template
standalone: true, // default in v19+, explicit in v17/18
imports: [CurrencyPipe], // everything the template references
templateUrl: './order-card.component.html',
styleUrl: './order-card.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush, // always
host: { 'class': 'order-card', '[class.is-paid]': 'order().status === "PAID"' },
})
export class OrderCardComponent { }
With signals it is effectively free, and it prevents an entire class of performance
problem. Retrofitting OnPush onto a large application later is genuinely
painful; enabling it on day one costs one line per component.
Signal inputs
import { Component, input, output, model, computed } from '@angular/core';
@Component({ /* ... */ })
export class OrderCardComponent {
// optional, with a default
readonly compact = input(false);
// required — the compiler errors if a caller omits it
readonly order = input.required<Order>();
// transform on the way in
readonly badgeCount = input(0, { transform: numberAttribute });
// rename the public attribute
readonly internalId = input<string>('', { alias: 'orderId' });
// derived state reads inputs like any other signal
readonly isOverdue = computed(() =>
this.order().status === 'PLACED' &&
Date.now() - Date.parse(this.order().placedAt) > 48 * 3600_000);
}
| Old | New | Gained |
|---|---|---|
@Input() order!: Order; | order = input.required<Order>() | Compile-time requirement, no ! lie |
@Input() set x(v) {…} | computed() off the input | No setter side effects |
ngOnChanges | effect() or computed() | Typed, granular, no SimpleChanges casting |
@Output() x = new EventEmitter() | x = output<T>() | No RxJS import, cannot leak |
Outputs and two-way binding
export class OrderCardComponent {
readonly order = input.required<Order>();
// an event the parent can listen to
readonly cancelled = output<number>();
readonly selected = output<Order>();
// two-way: parent writes [(expanded)]="isOpen"
readonly expanded = model(false);
cancel(): void {
this.cancelled.emit(this.order().id);
}
toggle(): void {
this.expanded.update(open => !open);
}
}
@for (order of orders(); track order.id) {
<app-order-card
[order]="order"
[compact]="density() === 'compact'"
[(expanded)]="expandedId"
(cancelled)="onCancel($event)"
(selected)="router.navigate(['/orders', $event.id])" />
}
(cancelled), (saved), (selectionChanged) — past
tense, describing a fact. (doCancel) or (onCancel) makes the
child dictate to the parent, which is exactly backwards and blocks reuse.
Content projection
The mechanism behind every reusable panel, dialog and card component.
@Component({
selector: 'app-panel',
standalone: true,
template: `
<section class="panel">
<header>
<ng-content select="[panelTitle]"></ng-content>
<ng-content select="[panelActions]"></ng-content>
</header>
<div class="body">
<!-- everything not matched above lands here -->
<ng-content></ng-content>
</div>
</section>
`,
})
export class PanelComponent {}
<app-panel> <h3 panelTitle>Order ORD-1042</h3> <button panelActions (click)="print()">Print</button> <p>This paragraph goes into the default slot.</p> </app-panel>
Lifecycle hooks
| Hook | Fires | Use it for |
|---|---|---|
constructor | On creation | inject() only — no work |
ngOnInit | After first inputs are set | Initial data load (or a resolver instead) |
ngOnChanges | On any input change | Legacy — prefer computed() |
afterNextRender | Once, after the DOM exists | Third-party DOM libraries, measuring |
afterRenderEffect | After every render | Rare; keep it cheap |
ngOnDestroy | On removal | Manual cleanup — often unnecessary now |
export class LiveTickerComponent {
private readonly destroyRef = inject(DestroyRef);
constructor() {
const id = setInterval(() => this.refresh(), 5000);
this.destroyRef.onDestroy(() => clearInterval(id));
// for observables, this is the idiomatic teardown
this.socket.messages$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(m => this.push(m));
}
}
With server-side rendering the component class runs in Node, where
document, window and localStorage do not exist. Put
any DOM access inside afterNextRender(), which only runs in the browser.
Querying the template
export class OrderFormComponent {
// a single element, optional
readonly searchBox = viewChild<ElementRef<HTMLInputElement>>('search');
// required — errors if it is missing
readonly submitBtn = viewChild.required<ElementRef>('submit');
// all matching children, as a signal of a readonly array
readonly rows = viewChildren(OrderRowComponent);
// projected content rather than the view
readonly tabs = contentChildren(TabComponent);
readonly rowCount = computed(() => this.rows().length);
focusSearch(): void {
this.searchBox()?.nativeElement.focus();
}
}
Smart and presentational components
Knows about the world
Injects services, loads data, handles navigation, owns state. Usually one per route. Hard to reuse — and that is fine.
Knows only its inputs
No injected services. Data in through input(), events out through
output(). Trivial to test and to reuse.
Keep the ratio heavily in favour of presentational components. A screen with one smart component and eight dumb ones is easy to change; eight smart components is a maintenance problem.
Which is the correct way to react to an input changing in modern Angular?
Signal inputs are signals, so computed() gives you derived state that
recalculates automatically and is type-safe. ngOnChanges still works but
hands you untyped SimpleChanges and fires for every input at once.