ProgrammingWeb Development

Angular Component Best Practices: OnPush, Signals and Clean Structure

Most Angular performance and maintenance problems start in components: too much logic in the template, inputs mutated from the inside, subscriptions that never end, and change detection running far more than needed. This guide collects the component practices that make the biggest difference in modern Angular (v17 and later), each with a short example.

1. Use standalone components

Standalone components declare their own dependencies, so you no longer need an NgModule for every feature. They are the default for new projects.

import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-order-card',
  standalone: true,
  imports: [DatePipe],
  templateUrl: './order-card.component.html',
  styleUrl: './order-card.component.scss',
})
export class OrderCardComponent {}

Each component’s imports array makes its dependencies explicit, which also helps tree-shaking and lazy loading.

2. Split smart and presentational components

A presentational (or “dumb”) component only receives data through inputs and reports user actions through outputs. A smart (container) component talks to services, holds state and passes data down.

// Presentational: no services, no HTTP
@Component({
  selector: 'app-order-list',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @for (order of orders(); track order.id) {
      <app-order-card [order]="order" (cancel)="cancel.emit(order.id)" />
    } @empty {
      <p>No orders yet.</p>
    }
  `,
  imports: [OrderCardComponent],
})
export class OrderListComponent {
  orders = input.required<Order[]>();
  cancel = output<string>();
}
// Smart: owns data loading and side effects
@Component({
  selector: 'app-orders-page',
  standalone: true,
  imports: [OrderListComponent],
  template: `<app-order-list [orders]="orders()" (cancel)="onCancel($event)" />`,
})
export class OrdersPageComponent {
  private api = inject(OrderApi);
  orders = toSignal(this.api.getOrders(), { initialValue: [] });

  onCancel(id: string) {
    this.api.cancel(id).subscribe();
  }
}

Presentational components become trivial to reuse and test, because they have no hidden dependencies.

3. Prefer signal inputs and outputs

The input(), input.required() and output() functions replace the @Input() and @Output() decorators. Inputs become read-only signals, so derived values are easy to express with computed:

export class PriceTagComponent {
  amount = input.required<number>();
  currency = input<'TRY' | 'EUR' | 'USD'>('TRY');

  formatted = computed(() =>
    new Intl.NumberFormat('tr-TR', { style: 'currency', currency: this.currency() }).format(this.amount()),
  );
}

There is no need for ngOnChanges to recalculate formatted; it updates automatically when either input changes.

4. Never mutate inputs

Inputs belong to the parent. If a child changes an input object in place, the parent’s state changes silently and OnPush components may not re-render. Emit an event instead and let the owner create a new object:

// Bad
toggleDone() {
  this.todo().done = !this.todo().done;
}

// Good
toggle = output<Todo>();
toggleDone() {
  this.toggle.emit({ ...this.todo(), done: !this.todo().done });
}

If a component really needs a value that both parent and child can change, use model(), which creates a two-way bindable signal ([(checked)]="isChecked").

5. Use OnPush change detection

With the default strategy, Angular checks every component on every browser event, timer and HTTP response. OnPush limits checks to when an input reference changes, an event fires inside the component, or a signal read in the template changes.

@Component({
  selector: 'app-order-card',
  changeDetection: ChangeDetectionStrategy.OnPush,
  // ...
})

OnPush works best together with immutable data and signals. Combined, they are also the path towards zoneless Angular.

6. Keep templates simple

Function calls in templates run on every change detection cycle:

<!-- Runs filterActive() on every check -->
@for (user of filterActive(users); track user.id) { ... }

Move the logic into a computed signal (or a pure pipe) so it only runs when the source changes:

activeUsers = computed(() => this.users().filter((u) => u.active));
@for (user of activeUsers(); track user.id) { ... }

Always provide a meaningful track expression in @for (usually an id). Tracking by $index causes Angular to re-create DOM nodes when items are reordered.

7. Clean up subscriptions

Subscriptions that outlive the component cause memory leaks and duplicated side effects. In modern Angular you rarely need ngOnDestroy for this:

export class LiveTickerComponent {
  private prices = inject(PriceStream);

  // Option A: convert to a signal; unsubscribes automatically
  latest = toSignal(this.prices.ticks$);

  // Option B: keep the subscription, but tie it to the component's lifetime
  constructor() {
    this.prices.alerts$.pipe(takeUntilDestroyed()).subscribe((a) => console.warn(a));
  }
}

The async pipe in templates is also safe, as it unsubscribes when the view is destroyed.

8. Use inject() and keep constructors light

inject() works in field initializers, which keeps dependencies next to where they are used and makes inheritance easier:

export class InvoiceComponent {
  private route = inject(ActivatedRoute);
  private api = inject(InvoiceApi);
}

Avoid doing heavy work in constructors. Put setup that depends on inputs in ngOnInit, or better, express it with computed and effect.

9. Use content projection for flexible layouts

Instead of adding more and more inputs to a component for every variation, let the parent project content into named slots:

@Component({
  selector: 'app-card',
  standalone: true,
  template: `
    <header><ng-content select="[card-title]" /></header>
    <section><ng-content /></section>
    <footer><ng-content select="[card-actions]" /></footer>
  `,
})
export class CardComponent {}
<app-card>
  <h3 card-title>Invoice #1024</h3>
  <p>Total: 1.450 TL</p>
  <button card-actions>Pay now</button>
</app-card>

10. Lazy load heavy parts with @defer

Charts, editors and maps can be loaded only when they are needed:

@defer (on viewport) {
  <app-sales-chart [data]="sales()" />
} @placeholder {
  <div class="chart-skeleton"></div>
} @loading (minimum 300ms) {
  <app-spinner />
}

The component and its dependencies are split into a separate chunk and downloaded when the placeholder scrolls into view.

11. Keep files small and focused

A good rule of thumb:

  • One component per file, with the template and styles in separate files once they exceed a few lines.
  • Feature folders (orders/, invoices/) rather than type folders (components/, services/).
  • If a component file grows beyond roughly 300 lines, it is usually doing two jobs. Split it.

12. Test components through their public API

Test what the component renders and emits, not its private methods:

it('emits cancel with the order id', () => {
  const fixture = TestBed.createComponent(OrderListComponent);
  fixture.componentRef.setInput('orders', [{ id: 'A1', total: 100 }]);
  fixture.detectChanges();

  let emitted: string | undefined;
  fixture.componentInstance.cancel.subscribe((id) => (emitted = id));

  fixture.nativeElement.querySelector('button.cancel').click();
  expect(emitted).toBe('A1');
});

componentRef.setInput works with both signal inputs and decorator inputs, so tests do not break when you migrate.

Checklist

  1. Standalone component with explicit imports.
  2. ChangeDetectionStrategy.OnPush.
  3. Signal input() / output(); never mutate inputs.
  4. Derived state in computed, not template function calls.
  5. track by a stable id in @for.
  6. Subscriptions via toSignal, async pipe or takeUntilDestroyed().
  7. Smart/presentational split for anything that loads data.
  8. @defer for heavy, below-the-fold UI.

Ahmet Rahmi Dokumacı

Software developer based in Istanbul, building products at FavolaSoft (favolasoft.com). I work with .NET, Angular, SQL Server and PostgreSQL and write about the problems I solve in real projects.

Related Articles

Leave a Reply

Back to top button