![](/img/trans.png)
[英]@ViewChildren(TemplateRef) is undefined for <template> elements
[英]ViewChildren with templateRef
我想使用ViewChildren
从TemplateRef
制作QueryList
,但不能传递给输入组件。
例如
组件.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'。
从模板中获取 cellTemplates 后,您应该强制父级检测更改,因此请尝试在父级中使用 ChangeDetectorRef:
export class AppComponent {
name = 'Angular';
@ViewChildren(TemplateRef, {read: TemplateRef}) cellTemplates: QueryList<TemplateRef<any>>;
constructor(private cd: ChangeDetectorRef) { }
ngOnInit(){ }
ngAfterViewInit(){
this.cd.detectChanges();
}
}
您可以在本文中找到有关该异常的详细说明。
在您的应用程序组件中,一个丑陋的解决方法是
<my-component *ngIf="yet" [templatesRef]="cellTemplates"></my-component>
实现 afterViewInit 并使用 setTimeout
export class AppComponent implements AfterViewInit {
yet=false;
ngAfterViewInit()
{
setTimeout(()=>{
this.yet=true
})
}
}
问题是,起初 cellTemplates 是一个空查询,而 afterViewInit 获取元素,
为什么不使用您创建的视图变量呢?
<my-component [templatesRef]="title"></my-component>
<ng-template #title>
ok
</ng-template>
另一种不使用ChangeDetectorRef
和setTimeout
的解决方案。
@ViewChildren(TemplateRef, {read: TemplateRef})
set cellTemplates(refs: QueryList<TemplateRef<any>>) {
this._cellTemplates = refs;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.