A common challenge faced by developers is managing dynamic content efficiently, particularly when dealing with lists and conditional rendering. This is a quick note on a practical implementation using template, change detection strategy and the @ViewChild
directive.
1. Using ngTemplateOutlet
for Dynamic Content#
ngTemplateOutlet
is a directive that allows Angular developers to inject templates into the DOM dynamically. This is especially useful when you want to render components based on conditions within a loop.
For example, to render a list of items using template. The template in this example is named as widget
:
<ng-container *ngFor="let card of cards" >
<ng-template
*ngTemplateOutlet="widget; context:{card : card}"
>
</ng-template>
</ng-container>
<ng-template #widget let-card="card">
Content of the card
</ng-template>
You may wondering why we need to extract the template out and not define it inline. In general, using template will be useful when you want to render similar content under different ngIf
conditions in a ngFor
loop.
2. Managing Change Detection in Angular#
When dealing with dynamic content, especially under the ChangeDetectionStrategy.OnPush
, Angular does not automatically check for changes in every cycle. This strategy assumes that the component and its children are immutable and will not change unless explicitly marked.
This strategy can lead to performance improvements but requires you to manually manage change detection. Here’s how you can handle it:
constructor(private cd: ChangeDetectorRef) {}
ngOnInit() {
// After some operations that change data
this.cd.markForCheck();
}
ViewChild
and Change Detection#
When using @ViewChild
in Angular, you need to be aware of how it interacts with ngIf
. If the child component is conditionally rendered (e.g. using ngIf
), the @ViewChild
needs the {static: false}
configuration (or it can be omitted as it defaults to false in Angular 9+):
@ViewChild('myChild', {static: false}) myChild;
Conclusion#
Understanding and effectively implementing templates and managing change detection are crucial for developing high-performance Angular applications. These strategies help in building dynamic interfaces more efficiently, making your application more responsive and easier to maintain.
Reference:
- https://blog.angular-university.io/angular-viewchild/
- https://www.stackhawk.com/blog/angular-content-security-policy-guide-what-it-is-and-how-to-enable-it/
- https://stackoverflow.com/questions/56359504/how-should-i-use-the-new-static-option-for-viewchild-in-angular-8
- https://angular.io/api/core/ViewChild#description
(cover image generated by ChatGPT.)