ViewChildren with templateRef

问题描述 投票:1回答:2

我想使用ViewChildrenQueryList生成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

angular dom angular8 viewchild
2个回答
0
投票

您应该在从模板获取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中找到有关该异常的详细说明。


0
投票

为什么不使用您创建的视图变量?

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

<ng-template #title>
    ok
</ng-template>
© www.soinside.com 2019 - 2024. All rights reserved.