Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the correct way to instantiate dynamically a template with @ViewChild querying a template reference variable?

I know I can just pass the template reference variable mytemplate to *ngTemplateOutlet and it works.

For learning purposes I want to use different approach via @ViewChild decorator.
However I got some errors that I don’t understand.

Minimal Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { Component, TemplateRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  template:
    `
<ng-template #mytemplate>
<p>Hello World</p>
</ng-template>
<ng-container *ngTemplateOutlet="template"></ng-container>
`
})
export class AppComponent {
  @ViewChild("mytemplate")
  template!: TemplateRef<any>;
}

Error Messages:

core.mjs:7640 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'. Find more at https://angular.io/errors/NG0100
    at throwErrorIfNoChangesMode (core.mjs:8207:11)
    at bindingUpdated (core.mjs:14552:17)
    at Module.ɵɵproperty (core.mjs:15284:9)
    at AppComponent_Template (app.component.ts:10:16)
    at executeTemplate (core.mjs:12121:9)
    at refreshView (core.mjs:11984:13)
    at refreshComponent (core.mjs:13080:13)
    at refreshChildComponents (core.mjs:11774:9)
    at refreshView (core.mjs:12034:13)
    at renderComponentOrTemplate (core.mjs:12101:9)

>Solution :

  1. This is the error which comes only in dev mode

  2. But still this should not be there in console.

  3. You can manually trigger change detection to avoid this issue

     constructor(private cd: ChangeDetectorRef) {}
    
     ngAfterViewChecked(){
         this.cd.detectChanges()
     }
    

Link to documnetation : https://angular.io/errors/NG0100

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading