Complete the code to set the OnPush change detection strategy in an Angular component.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-sample', template: `<p>Hello OnPush!</p>`, changeDetection: ChangeDetectionStrategy.[1] }) export class SampleComponent {}
The OnPush strategy tells Angular to check the component only when its inputs change or an event occurs inside it.
Complete the code to inject ChangeDetectorRef and mark the component for check.
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-checker', template: `<button (click)="update()">Update</button>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class CheckerComponent { constructor(private cdr: [1]) {} update() { // some update logic this.cdr.markForCheck(); } }
ChangeDetectorRef is used to manually trigger change detection or mark the component to be checked.
Fix the error in the code by completing the blank with the correct input decorator.
import { Component, Input, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-child', template: `<p>{{ data }}</p>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class ChildComponent { [1] data!: string; }
The @Input decorator marks a property as an input that can receive data from a parent component, which triggers OnPush change detection.
Fill both blanks to create a pure pipe that works well with OnPush strategy.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'custom', pure: [1] }) export class CustomPipe implements PipeTransform { transform(value: string): string { return value.toUpperCase(); } } // Usage in template: {{ 'hello' | custom }}
Pure pipes are set with pure: true by default and work efficiently with OnPush change detection.
Fill all three blanks to complete the code that triggers change detection manually in an OnPush component.
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-manual', template: `<button (click)="refresh()">Refresh</button>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class ManualComponent { constructor(private [1]: ChangeDetectorRef) {} refresh() { // some data update logic this.[1].[2](); } ngAfterViewChecked() { this.[3].detectChanges(); } }
The ChangeDetectorRef instance is commonly named cdr. Calling markForCheck() marks the component for checking, and detectChanges() triggers immediate change detection.