Performance: Async pipe for template subscriptions
This affects how Angular handles observable subscriptions in templates, impacting rendering speed and memory usage.
export class MyComponent { data$ = this.service.getData(); constructor(private service: DataService) {} } <!-- Template --> <div>{{ data$ | async }}</div>
import { Subscription } from 'rxjs'; export class MyComponent { data: any; subscription: Subscription; constructor(private service: DataService) {} ngOnInit() { this.subscription = this.service.getData().subscribe(value => { this.data = value; }); } ngOnDestroy() { this.subscription.unsubscribe(); } } <!-- Template --> <div>{{ data }}</div>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual subscription with property binding | Multiple DOM updates as data changes | Triggers reflow on each update | Moderate paint cost due to frequent updates | [X] Bad |
| Async pipe in template | Single DOM update per data emission | Minimal reflows triggered | Lower paint cost due to optimized updates | [OK] Good |
async pipe in Angular templates?data$?| followed by async in the template interpolation.{{ data$ | async }} to unwrap the Observable data$.data$ = of('Hello');<div>{{ data$ | async }}</div>data$ emits the string 'Hello' immediately.<div>{{ data | async() }}</div>data is an Observable.async() with parentheses is invalid and causes a template error.user$ that emits user objects. You want to display the user's name in the template and also show a loading message while waiting for data. Which template code correctly uses the async pipe and handles loading state?*ngIf="user$ | async as user" unwraps the Observable and assigns the emitted value to user.else loading shows the loading message while waiting for data.Pass the test and this pattern moves unknown