首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ViewChildren与templateRef

ViewChildren与templateRef
EN

Stack Overflow用户
提问于 2019-10-08 07:02:37
回答 4查看 5.1K关注 0票数 2

我想使用ViewChildren make QueryListTemplateRef,但不能传递到输入组件。

例如

Component.ts:

代码语言:javascript
复制
@ViewChildren(TemplateRef) cellTemplates: QueryList<TemplateRef<any>>;

查看:

代码语言:javascript
复制
<my-component [templatesRef]="cellTemplates"></my-component>

投入:

代码语言:javascript
复制
_templatesRef;
@Input()
set templatesRef(refs: any) {
   this._templatesRef = refs;
}

ExpressionChangedAfterItHasBeenCheckedError:表达式检查后发生了更改。先前的值:'ngIf: false‘。当前值:'ngIf: true‘。

斯塔克比利茨

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-10-08 07:28:33

在从模板获取cellTemplates之后,应该强制父级检测更改,因此尝试在父级中使用ChangeDetectorRef:

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

您可以在这个文章中找到关于该异常的详细解释。

票数 4
EN

Stack Overflow用户

发布于 2019-10-08 08:13:28

在您的应用程序组件中,有一个很难看的工作。

代码语言:javascript
复制
<my-component *ngIf="yet" [templatesRef]="cellTemplates"></my-component>

实现afterViewInit并使用setTimeout

代码语言:javascript
复制
export class AppComponent implements AfterViewInit  {
  yet=false;

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

问题是,最初cellTemplates是一个空查询,afterViewInit get元素,

票数 2
EN

Stack Overflow用户

发布于 2019-10-08 07:43:47

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

代码语言:javascript
复制
<my-component [templatesRef]="title"></my-component>

<ng-template #title>
    ok
</ng-template>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58281557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档