简体   繁体   English

ViewChildren 与 templateRef

[英]ViewChildren with templateRef

I want to use ViewChildren make QueryList from TemplateRef , but can't pass to input component.我想使用ViewChildrenTemplateRef制作QueryList ,但不能传递给输入组件。

For example例如

Component.ts:组件.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. ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。 Previous value: 'ngIf: false'.以前的值:'ngIf: false'。 Current value: 'ngIf: true'.当前值:'ngIf: true'。

See in Stackbilitz斯塔克比利茨

You should force parent to detect changes after getting the cellTemplates from template, so try to use ChangeDetectorRef in parent:从模板中获取 cellTemplates 后,您应该强制父级检测更改,因此请尝试在父级中使用 ChangeDetectorRef:

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演示

An ugly work around is, in your app-component在您的应用程序组件中,一个丑陋的解决方法是

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

Implements afterViewInit and use a setTimeout实现 afterViewInit 并使用 setTimeout

export class AppComponent implements AfterViewInit  {
  yet=false;

  ngAfterViewInit()
  {
    setTimeout(()=>{
      this.yet=true
    })
  }
}

The problem is that at first cellTemplates is a empty query and afterViewInit get elements,问题是,起初 cellTemplates 是一个空查询,而 afterViewInit 获取元素,

Why not use the view variable you created instead?为什么不使用您创建的视图变量呢?

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

<ng-template #title>
    ok
</ng-template>

Another solution without using ChangeDetectorRef & setTimeout .另一种不使用ChangeDetectorRefsetTimeout的解决方案。

@ViewChildren(TemplateRef, {read: TemplateRef})
set cellTemplates(refs: QueryList<TemplateRef<any>>) {
    this._cellTemplates = refs;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM