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? |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
No comments:
Post a Comment