Chapter 03

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.

⏱ 16 min readLevel: beginner → intermediateCore chapter

Anatomy

order-card.component.ts
@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 { }
Use OnPush everywhere, from the start

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

the modern API
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);
}
OldNewGained
@Input() order!: Order;order = input.required<Order>()Compile-time requirement, no ! lie
@Input() set x(v) {…}computed() off the inputNo setter side effects
ngOnChangeseffect() or computed()Typed, granular, no SimpleChanges casting
@Output() x = new EventEmitter()x = output<T>()No RxJS import, cannot leak

Outputs and two-way binding

child → parent
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);
  }
}
parent template
@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])" />
}
Name outputs after what happened, not what to do

(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.

panel.component.ts
@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 {}
using it
<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

HookFiresUse it for
constructorOn creationinject() only — no work
ngOnInitAfter first inputs are setInitial data load (or a resolver instead)
ngOnChangesOn any input changeLegacy — prefer computed()
afterNextRenderOnce, after the DOM existsThird-party DOM libraries, measuring
afterRenderEffectAfter every renderRare; keep it cheap
ngOnDestroyOn removalManual cleanup — often unnecessary now
cleanup without ngOnDestroy
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));
  }
}
SSR: no document or window in the constructor

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

signal queries (v17.2+)
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

Smart / container

Knows about the world

Injects services, loads data, handles navigation, owns state. Usually one per route. Hard to reuse — and that is fine.

Presentational

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.