Skip to main content

Learning Angular: Template, Change Detection and ViewChild

·335 words·2 mins
Hong Konger.

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" >
        *ngTemplateOutlet="widget; context:{card : card}"

<ng-template #widget let-card="card">
  Content of the card

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;

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.


(cover image generated by ChatGPT.)


Adding Audio to Your Web App: The Complete Guide
·1389 words·7 mins
Sound, rhythm, and harmony find their way into the inward places of the soul.
Understanding Content Security Policy (CSP) for Azure App Service and Angular Apps
·312 words·2 mins
Securing Azure App Service and Angular Apps with CSP.
Learning React: Updating Component State in componentDidMount()
·395 words·2 mins
Hey I just met you and this is crazy. But here’s my data so have a callback, maybe.