我想使用ViewChildren
从QueryList
生成TemplateRef
,但无法传递到输入组件。
例如
Component.ts:
@ViewChildren(TemplateRef) cellTemplates: QueryList<TemplateRef<any>>;
查看:
<my-component [templatesRef]="cellTemplates"></my-component>
输入:
_templatesRef;
@Input()
set templatesRef(refs: any) {
this._templatesRef = refs;
}
ExpressionChangedAfterItHasBeenCheckedError:表达式已更改经过检查后。先前的值:'ngIf:false'。当前值:'ngIf:true'。
请参见Stackbilitz
您应该在从模板获取cellTemplates后强制父级检测更改,因此请尝试在父级中使用ChangeDetectorRef:
export class AppComponent { name = 'Angular'; @ViewChildren(TemplateRef, {read: TemplateRef}) cellTemplates: QueryList<TemplateRef<any>>; constructor(private cd: ChangeDetectorRef) { } ngOnInit(){ } ngAfterViewInit(){ this.cd.detectChanges(); } }
您可以在此article中找到有关该异常的详细说明。
为什么不使用您创建的视图变量?
<my-component [templatesRef]="title"></my-component>
<ng-template #title>
ok
</ng-template>