【问题标题】:ViewChildren with templateRefViewChildren 与 templateRef
【发布时间】:2020-02-05 10:59:09
【问题描述】:

我想使用ViewChildrenQueryListTemplateRef 转换成TemplateRef,但无法传递给输入组件。

例如

组件.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


【解决方案1】:

不使用ChangeDetectorRef & setTimeout 的另一种解决方案。

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

【讨论】:

    【解决方案2】:

    一个丑陋的解决方法是,在您的应用程序组件中

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

    实现 afterViewInit 并使用 setTimeout

    export class AppComponent implements AfterViewInit  {
      yet=false;
    
      ngAfterViewInit()
      {
        setTimeout(()=>{
          this.yet=true
        })
      }
    }
    

    问题是,一开始 cellTemplates 是一个空查询,而 afterViewInit 获取元素,

    【讨论】:

    • 我真的很喜欢你的方法-detectChanges-,但我不确定(还),谢谢你的链接。对我来说,给 Angular 一个“呼吸”比使用 detectChanges 更自然。让我转一下
    【解决方案3】:

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

    <my-component [templatesRef]="title"></my-component>
    
    <ng-template #title>
        ok
    </ng-template>
    

    【讨论】:

    • 我有几个模板,我需要获取所有模板。
    【解决方案4】:

    在从模板中获取 cellTemplates 后,你应该强制 parent 检测变化,所以尝试在 parent 中使用 ChangeDetectorRef:

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

    您可以在此article 中找到有关该异常的详细说明。

    DEMO ??

    【讨论】:

    • 谢谢,但有更好的解决方案setter
    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 2019-10-25
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2017-04-03
    • 2017-06-11
    相关资源
    最近更新 更多