Search code examples
angulardomangular8viewchild

ViewChildren with templateRef


I want to use ViewChildren make QueryList from TemplateRef, but can't pass to input component.

For example

Component.ts:

@ViewChildren(TemplateRef) cellTemplates: QueryList<TemplateRef<any>>;

View:

<my-component [templatesRef]="cellTemplates"></my-component>

Input :

_templatesRef;
@Input()
set templatesRef(refs: any) {
   this._templatesRef = refs;
}

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'.

See in Stackbilitz


Solution

  • You should force parent to detect changes after getting the cellTemplates from template, so try to use ChangeDetectorRef in parent:

    export class AppComponent  {
      name = 'Angular';
      @ViewChildren(TemplateRef, {read: TemplateRef}) cellTemplates: QueryList<TemplateRef<any>>;
      constructor(private cd: ChangeDetectorRef) { }
      ngOnInit(){ }
      ngAfterViewInit(){
        this.cd.detectChanges();
      }
    }
    

    You can find detailed explanations about that exception in this article.

    DEMO 🚀🚀