Angular 使用templateRef查看子对象

Angular 使用templateRef查看子对象,angular,dom,angular8,viewchild,Angular,Dom,Angular8,Viewchild,我想从TemplateRef使用ViewChildren生成QueryList,但无法传递到输入组件 比如说 组件1.ts: @ViewChildren(TemplateRef) cellTemplates: QueryList<TemplateRef<any>>; ExpressionChangedTerithasBeenCheckedError:表达式已更改 检查过之后。上一个值:“ngIf:false”。当前值: “ngIf:对” 请参见从模板中获取cellTem

我想从
TemplateRef
使用
ViewChildren
生成
QueryList
,但无法传递到输入组件

比如说

组件1.ts:

@ViewChildren(TemplateRef) cellTemplates: QueryList<TemplateRef<any>>;
ExpressionChangedTerithasBeenCheckedError:表达式已更改 检查过之后。上一个值:“ngIf:false”。当前值: “ngIf:对”


请参见

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

export class AppComponent  {
  name = 'Angular';
  @ViewChildren(TemplateRef, {read: TemplateRef}) cellTemplates: QueryList<TemplateRef<any>>;
  constructor(private cd: ChangeDetectorRef) { }
  ngOnInit(){ }
  ngAfterViewInit(){
    this.cd.detectChanges();
  }
}
导出类AppComponent{
名称='角度';

@ViewChildren(TemplateRef,{read:TemplateRef})cellTemplates:QueryList为什么不使用您创建的视图变量

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

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

好啊

在你的应用程序组件中,一个难看的解决方法是

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

问题在于,首先cellTemplates是一个空查询,在ViewInit获取元素之后,

是另一个不使用
ChangeDetectorRef
setTimeout
的解决方案

@ViewChildren(TemplateRef, {read: TemplateRef})
set cellTemplates(refs: QueryList<TemplateRef<any>>) {
    this._cellTemplates = refs;
}
@ViewChildren(TemplateRef,{read:TemplateRef})
设置单元格模板(参考:QueryList){
这是。_cellTemplates=refs;
}

请提供您的完整代码,而不是您认为相关的代码。更好的是,提供一个复制您的问题的代码。@Maryannah是的,是的,谢谢。我有几个模板,我需要获取所有模板。我真的喜欢您的方法-检测更改-,但我还不确定,谢谢您的链接。对我来说,这更自然,让我“喘口气”使用角度变换比使用检测变换更有效。让我来谈谈角度变换,但有一个更好的解决方案
setter
<my-component *ngIf="yet" [templatesRef]="cellTemplates"></my-component>
export class AppComponent implements AfterViewInit  {
  yet=false;

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