Skip to content

Nairobi · East Africa

Frontend Development

Best Angular Development Practices in 2026

Modern Angular: standalone components, signals, @if and @for, deferrable views, inject(), typed forms, SSR with hydration and zoneless change detection.

TechBytes EA Engineering Team· · 10 min read

Colourful source code on a monitor

Angular has changed more in the last few major versions than in the five years before them. Standalone components, signals, built-in control flow, deferrable views, incremental hydration and zoneless change detection have reshaped what a well-written Angular application looks like. Many codebases in banks, telcos and enterprises across East Africa still carry patterns from the NgModule and Zone.js era. This guide sets out the practices we recommend for new Angular work in 2026, with correct, modern code you can adopt directly, and a migration path for existing applications.

Key takeaways

  • Build with standalone components and functional providers; NgModules are no longer needed for new code.
  • Use signals for component and service state, computed() for derived values and signal-based input(), output() and model() APIs.
  • Use built-in control flow (@if, @for with track, @switch, @let) and deferrable views (@defer) to reduce bundle size and template noise.
  • Prefer inject(), functional guards and functional interceptors.
  • Enable SSR with hydration for public-facing apps, and adopt zoneless change detection for leaner, more predictable rendering.

Project setup and application configuration

New projects created with the Angular CLI use standalone components by default, and recent versions generate zoneless applications by default. Configuration lives in a typed ApplicationConfig object rather than a root module.

// src/app/app.config.ts
import { ApplicationConfig, provideZonelessChangeDetection } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { provideClientHydration, withIncrementalHydration } from '@angular/platform-browser';

import { routes } from './app.routes';
import { authInterceptor } from './core/auth.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZonelessChangeDetection(),
    provideRouter(routes, withComponentInputBinding()),
    provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
    provideClientHydration(withIncrementalHydration()),
  ],
};
// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';

bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));

A note on versions: provideZonelessChangeDetection() is the stable name in current Angular. In versions before 20 it was provideExperimentalZonelessChangeDetection(). If your project is on an older release, upgrade first using the official update guide at angular.dev.

Enable strict mode

Keep strict: true in tsconfig.json and strictTemplates: true in angularCompilerOptions. Strict templates catch type errors in bindings at build time, which is where many production bugs in Angular apps originate.

Source code displayed on a monitorReadable, typed code is what keeps a front end maintainable as the team grows.

Standalone components

Since Angular 19, components are standalone by default, so you no longer write standalone: true. Each component declares exactly what it uses in imports, which makes dependencies explicit and enables better tree shaking.

// src/app/wallet/transaction-list.component.ts
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { CurrencyPipe, DatePipe } from '@angular/common';

export interface Transaction {
  id: string;
  direction: 'in' | 'out';
  amount: number;
  counterparty: string;
  createdAt: string;
}

@Component({
  selector: 'app-transaction-list',
  imports: [CurrencyPipe, DatePipe],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @let rows = filtered();
    <p>{{ rows.length }} transactions, net {{ net() | currency: 'KES' }}</p>
    <ul>
      @for (tx of rows; track tx.id) {
        <li (click)="selected.emit(tx)">
          {{ tx.createdAt | date: 'medium' }} - {{ tx.counterparty }}:
          {{ tx.direction === 'in' ? '+' : '-' }}{{ tx.amount | currency: 'KES' }}
        </li>
      } @empty {
        <li>No transactions in this period.</li>
      }
    </ul>
  `,
})
export class TransactionListComponent {
  readonly transactions = input.required<Transaction[]>();
  readonly direction = input<'all' | 'in' | 'out'>('all');
  readonly selected = output<Transaction>();

  readonly filtered = computed(() => {
    const dir = this.direction();
    const all = this.transactions();
    return dir === 'all' ? all : all.filter((t) => t.direction === dir);
  });

  readonly net = computed(() =>
    this.filtered().reduce((sum, t) => sum + (t.direction === 'in' ? t.amount : -t.amount), 0),
  );
}

Practices shown here:

  • input.required<T>() and input<T>(default) replace @Input(), and they are signals, so derived values use computed().
  • output<T>() replaces @Output() with EventEmitter.
  • OnPush remains good practice. With signals and zoneless change detection, Angular knows precisely which components need refreshing.
  • @for requires a track expression. Track by a stable identifier, never by the object itself for data that is re-fetched.
  • @let declares a template-local variable, avoiding repeated calls and async pipe gymnastics.

For two-way binding, use model<T>(), which creates a writable signal input that parents can bind with [(value)].

Signals for state

Signals are now the primary reactivity primitive. Use them for local component state and for shared state in services.

// src/app/wallet/wallet.store.ts
import { Injectable, computed, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Transaction } from './transaction-list.component';

@Injectable({ providedIn: 'root' })
export class WalletStore {
  private readonly http = inject(HttpClient);

  private readonly _transactions = signal<Transaction[]>([]);
  private readonly _loading = signal(false);
  private readonly _error = signal<string | null>(null);

  readonly transactions = this._transactions.asReadonly();
  readonly loading = this._loading.asReadonly();
  readonly error = this._error.asReadonly();
  readonly balance = computed(() =>
    this._transactions().reduce((sum, t) => sum + (t.direction === 'in' ? t.amount : -t.amount), 0),
  );

  load(): void {
    this._loading.set(true);
    this._error.set(null);
    this.http.get<Transaction[]>('/api/transactions').subscribe({
      next: (txs) => {
        this._transactions.set(txs);
        this._loading.set(false);
      },
      error: () => {
        this._error.set('Could not load transactions. Check your connection and try again.');
        this._loading.set(false);
      },
    });
  }
}

Guidelines:

  • Expose read-only signals and keep writable signals private. Mutations go through methods.
  • Use computed() for derived state, never effect() to copy one signal into another.
  • Use effect() sparingly, for genuine side effects such as logging, analytics or synchronising with browser APIs.
  • Keep RxJS where it shines: debouncing search input, websockets, retry with backoff, combining streams. Bridge with toSignal() and toObservable() from @angular/core/rxjs-interop.
  • Angular also provides linkedSignal() for writable state that resets when a source changes, and resource APIs (resource(), httpResource()) for async data as signals. Check the current stability status of resource APIs on angular.dev before relying on them in production.

For very large applications with complex cross-cutting state, NgRx SignalStore is a popular structured option built on the same primitives.

Dependency injection with inject()

inject() replaces constructor injection in most cases. It works in field initialisers, which keeps classes concise, and it is the only way to get dependencies in functional guards, resolvers and interceptors.

// src/app/core/auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();
  if (!token || !req.url.startsWith('/api/')) {
    return next(req);
  }
  return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};
// src/app/core/auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  return auth.isLoggedIn() ? true : inject(Router).createUrlTree(['/login']);
};

Note the interceptor only attaches the token to your own API. Leaking bearer tokens to third-party domains is a common and serious mistake.

Routing and lazy loading

Lazy-load feature areas with loadComponent or loadChildren:

// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './core/auth.guard';

export const routes: Routes = [
  { path: '', loadComponent: () => import('./home/home.component').then((m) => m.HomeComponent) },
  {
    path: 'wallet',
    canActivate: [authGuard],
    loadChildren: () => import('./wallet/wallet.routes').then((m) => m.WALLET_ROUTES),
  },
  { path: '**', redirectTo: '' },
];

With withComponentInputBinding(), route parameters and query parameters bind directly to component inputs, removing boilerplate ActivatedRoute subscriptions.

Deferrable views

@defer lazily loads a block of the template and its dependencies, based on triggers such as on viewport, on idle, on interaction or on timer. It is one of the most effective tools for users on mid-range phones and mobile data.

@defer (on viewport; prefetch on idle) {
  <app-spending-chart [transactions]="store.transactions()" />
} @placeholder (minimum 300ms) {
  <div class="chart-skeleton">Spending chart</div>
} @loading (after 150ms) {
  <p>Loading chart...</p>
} @error {
  <p>Chart could not be loaded.</p>
}

Good candidates for deferral: charts, maps, rich text editors, comment sections and anything below the fold. Components used inside a @defer block must be standalone and not referenced elsewhere in the eagerly loaded template, or they will be bundled eagerly.

Typed reactive forms

Reactive forms are fully typed. Use NonNullableFormBuilder so that controls reset to their initial values rather than null.

// src/app/wallet/top-up-form.component.ts
import { Component, inject, output } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

const MIN_TOP_UP_KES = 10;
const MAX_TOP_UP_KES = 100_000; // set from your business and provider rules

@Component({
  selector: 'app-top-up-form',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="submit()">
      <label>
        M-Pesa number (2547XXXXXXXX or 2541XXXXXXXX)
        <input formControlName="phone" inputmode="numeric" autocomplete="tel" />
      </label>
      @if (form.controls.phone.touched && form.controls.phone.invalid) {
        <p class="error">Enter a valid Kenyan mobile number in 254 format.</p>
      }
      <label>
        Amount (KES)
        <input type="number" formControlName="amount" />
      </label>
      <button type="submit" [disabled]="form.invalid">Send STK push</button>
    </form>
  `,
})
export class TopUpFormComponent {
  private readonly fb = inject(NonNullableFormBuilder);
  readonly submitted = output<{ phone: string; amount: number }>();

  readonly form = this.fb.group({
    phone: ['', [Validators.required, Validators.pattern(/^254(7|1)\d{8}$/)]],
    amount: [100, [Validators.required, Validators.min(MIN_TOP_UP_KES), Validators.max(MAX_TOP_UP_KES)]],
  });

  submit(): void {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    // getRawValue() is typed as { phone: string; amount: number }
    this.submitted.emit(this.form.getRawValue());
    this.form.reset();
  }
}

Client-side validation is for user experience only. The server must re-validate every field before calling the Daraja STK push API; see our guide on building modern web applications with TypeScript for validating at boundaries. Angular has also been developing signal-based forms; check their status on angular.dev before adopting them for production.

Overhead view of a developer workstation with code on two monitorsA typical engineering setup: editor, terminal and the running app side by side.

Server-side rendering and hydration

For public pages, add SSR with ng add @angular/ssr (or choose it when creating the project). With hydration enabled, Angular reuses the server-rendered DOM instead of re-creating it, avoiding flicker. Event replay captures user clicks made before hydration completes and replays them, which matters on slower devices.

Incremental hydration goes further: combined with @defer, you can leave server-rendered sections dehydrated until they are needed.

@defer (hydrate on viewport) {
  <app-product-reviews [productId]="productId()" />
} @placeholder {
  <div>Reviews</div>
}

SSR checklist:

  • Do not access window, document or localStorage directly in code that runs on the server. Use afterNextRender() for browser-only work, or inject DOCUMENT and PLATFORM_ID where needed.
  • HTTP requests made during SSR are cached and transferred to the client by default with HttpClient, so data is not fetched twice. Requests with authorisation headers are excluded by default; review withHttpTransferCacheOptions() carefully before caching any cookie-authenticated or user-specific responses.
  • Deploy the Node server close to your users. If most traffic is in Kenya, consider local hosting or the nearest cloud region, and put static assets behind a CDN with African points of presence.

Zoneless change detection

Zone.js patched browser APIs to trigger change detection after any async event, which was convenient but imprecise and added bundle weight. In zoneless mode, Angular schedules change detection when signals used in templates change, when event listeners bound in templates fire, when the async pipe receives values, or when you call markForCheck().

To migrate an existing application:

  1. Move component state to signals, or ensure components use OnPush and call markForCheck() where they mutate state outside template events.
  2. Remove reliance on NgZone.onStable and onMicrotaskEmpty.
  3. Add provideZonelessChangeDetection() to the application providers.
  4. Remove zone.js from the polyfills in angular.json and uninstall it if nothing else needs it.
  5. Run end-to-end tests thoroughly, especially screens that update from timers, websockets or third-party libraries.

Other practices worth adopting

  • Host bindings in metadata: prefer the host property in @Component over @HostBinding and @HostListener.
  • NgOptimizedImage: use the ngSrc directive for images to get lazy loading, sizing warnings and priority hints.
  • Testing: use the CLI's current default test runner (recent versions have moved to Vitest), Angular Testing Library for user-centred component tests and Playwright or Cypress for end-to-end tests.
  • Schematics for migrations: the Angular CLI provides automated migrations to standalone, control flow, signal inputs and inject(). Run them on a branch and review the diff.
  • Budgets: set bundle size budgets in angular.json and fail the build when they are exceeded.

Common mistakes

  • Using effect() to derive state. It causes extra change detection cycles and subtle bugs. Use computed().
  • Tracking @for by object identity for data fetched from an API, which destroys and recreates DOM on every refresh.
  • Mixing NgModules and standalone patterns indefinitely. Plan to finish migrations so new developers see one way of working.
  • Touching browser globals during SSR, causing server crashes or hydration mismatches.
  • Trusting client-side validation for payments and financial operations.
  • Skipping updates. Angular's six-monthly major releases are designed to be incremental. Falling several versions behind makes upgrades much harder.

FAQ

Should I still use RxJS in Angular?

Yes, for event streams, websockets and complex async coordination. Use signals for state and template binding, and bridge the two with toSignal() and toObservable().

Do I need to migrate an existing app to standalone?

It is strongly recommended. The CLI's migration schematic automates most of the work, and it unlocks deferrable views and simpler lazy loading.

Is zoneless ready for production?

Zoneless change detection is stable in current Angular and is the default for new projects. Existing applications should migrate gradually, starting with signals and OnPush.

Is Angular SSR worth it for internal apps?

Usually not. SSR mainly benefits public pages, SEO and first-load performance. Internal dashboards behind login often work well as client-rendered apps with good lazy loading.

How TechBytes can help

We build new Angular applications and modernise existing ones, including migrations to standalone components, signals, SSR and zoneless change detection, with test coverage to keep releases safe. Our software development team can audit your codebase and plan an incremental upgrade path. If you are still choosing a framework, see our comparison of Angular vs React vs Vue.

WhatsApp