簡體   English   中英

ViewChildren 與 templateRef

[英]ViewChildren with templateRef

我想使用ViewChildrenTemplateRef制作QueryList ,但不能傳遞給輸入組件。

例如

組件.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'。

斯塔克比利茨

從模板中獲取 cellTemplates 后,您應該強制父級檢測更改,因此請嘗試在父級中使用 ChangeDetectorRef:

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

您可以在本文中找到有關該異常的詳細說明。

演示

在您的應用程序組件中,一個丑陋的解決方法是

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

實現 afterViewInit 並使用 setTimeout

export class AppComponent implements AfterViewInit  {
  yet=false;

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

問題是,起初 cellTemplates 是一個空查詢,而 afterViewInit 獲取元素,

為什么不使用您創建的視圖變量呢?

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

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

另一種不使用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