Performance: Route parameters with ActivatedRoute
This affects the speed of rendering components that depend on route parameters and the responsiveness of route changes.
readonly id = this.route.params.pipe( map(params => params['id']), distinctUntilChanged() ); // Use async pipe in template: {{ id | async }}
constructor(private route: ActivatedRoute) {
this.route.params.subscribe(params => {
this.loadData(params['id']);
});
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual subscription without operators | Multiple redundant updates | Multiple reflows on each route change | High paint cost due to repeated DOM updates | [X] Bad |
| Using async pipe with distinctUntilChanged | Updates only on parameter change | Single reflow per unique change | Minimal paint cost | [OK] Good |
ActivatedRoute in Angular?ActivatedRoute?paramMap, not params or others.paramMap, use get('id') to retrieve the parameter value.constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.userId = params.get('userId');
});
}/profile/42 and the route is defined as { path: 'profile/:userId' }, what will be the value of this.userId after initialization?paramMap.get() method always returns a string or null if not found.profile/:userId matches URL /profile/42, so userId is '42'.ngOnInit() {
this.route.paramMap.subscribe(params => {
this.id = params.get('id');
});
}/product with no id parameter. What issue will occur?paramMap.get() returns null, not an error.this.id becomes null.postId changes without recreating the component. Which approach correctly handles this using ActivatedRoute?ngOnInit runs once.paramMap lets you react to parameter changes dynamically without recreating the component.snapshot.paramMap reads parameters only once and won't update if params change while component is active.Pass the test and this pattern moves unknown