Complete the code to create a standalone Angular component with OnPush change detection.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-sample', template: `<p>Sample works!</p>`, changeDetection: ChangeDetectionStrategy.[1], standalone: true }) export class SampleComponent {}
The OnPush strategy tells Angular to check the component only when its inputs change or an event occurs, improving performance.
Complete the code to inject the ChangeDetectorRef and mark the component for check.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-checker', template: `<button (click)="update()">Update</button>`, standalone: true }) export class CheckerComponent { constructor(private cdr: ChangeDetectorRef) {} update() { // some update logic this.cdr.[1](); } }
markForCheck() tells Angular to check this component and its ancestors during the next change detection cycle.
Fix the error in the code to prevent unnecessary change detection cycles.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-list', template: `<ul><li *ngFor="let item of items">{{item}}</li></ul>`, changeDetection: ChangeDetectionStrategy.[1], standalone: true }) export class ListComponent { items = [1, 2, 3]; addItem(newItem: number) { this.items.push(newItem); } }
Using Default change detection ensures Angular notices changes when the array is mutated directly. OnPush requires immutable data changes.
Fill both blanks to create an immutable update and use OnPush change detection.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-items', template: `<ul><li *ngFor="let item of items">{{item}}</li></ul>`, changeDetection: ChangeDetectionStrategy.[1], standalone: true }) export class ItemsComponent { items = [1, 2, 3]; addItem(newItem: number) { this.items = this.items.[2]([newItem]); } }
Using OnPush with immutable updates like concat creates a new array reference, triggering change detection.
Fill all three blanks to optimize change detection with a trackBy function in *ngFor.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-users', template: ` <ul> <li *ngFor="let user of users; trackBy: [1]">{{user.name}}</li> </ul> `, changeDetection: ChangeDetectionStrategy.[2], standalone: true }) export class UsersComponent { users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]; [3](index: number, user: { id: number; name: string }) { return user.id; } }
Using OnPush with a trackBy function like trackById helps Angular optimize rendering by tracking items by their unique id.