Use OnPush change detection can provide best example to use in Angular

 

Example: Optimizing a User Profile Component with OnPush using Angular 


Let’s create a component that displays user data and updates efficiently using OnPush change detection.


1. Component Definition (OnPush Strategy)


import { Component, Input, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-user-profile',
  template: `
    <div class="user-card">
      <h2>{{ user.name }}</h2>
      <p>Email: {{ user.email }}</p>
      <p>Last Updated: {{ lastUpdated | date:'medium' }}</p>
      <button (click)="updateTimestamp()">Update Timestamp</button>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush // Enable OnPush
})
export class UserProfileComponent {
  @Input() user!: { name: string; email: string };
  lastUpdated: Date = new Date();

  // Only triggers change detection for click events
  updateTimestamp() {
    this.lastUpdated = new Date(); // Local state change
  }
}


2. Parent Component Usage



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

@Component({
  selector: 'app-parent',
  template: `
    <app-user-profile 
      [user]="currentUser"
    ></app-user-profile>

    <button (click)="updateUserImmutable()">Update User (Immutable)</button>
    <button (click)="updateUserMutable()">Update User (Mutable)</button>
  `
})
export class ParentComponent {
  currentUser = { name: 'Alice', email: 'alice@example.com' };

  // Good: Immutable update (triggers OnPush detection)
  updateUserImmutable() {
    this.currentUser = { 
      ...this.currentUser, 
      name: 'Updated Alice' 
    };
  }

  // Bad: Mutation (OnPush won't detect this change)
  updateUserMutable() {
    this.currentUser.name = 'Mutated Alice';
  }
}

Key Behaviors with OnPush


Action

Result

Why?

  • Click "Update Timestamp" button

  • Component updates
  • (click) event triggers change detection.
  • Click "Update User (Immutable)"
  • Component updates
  • Input reference changes (immutable update).
  • Click "Update User (Mutable)"
  • No update
  • Input object reference remains the same.
  • External API data change
  • No update (unless input reference changes)
  • OnPush only checks input changes or explicit triggers

No comments:

Post a Comment

Angular URL serializer to properly handle URLs that start with query parameters directly (without a path adding trailing slashes Angular

 Example Code The key requirement: In the parse method, I added special handling for URLs that start with query parameters: If the URL start...

Best for you