簡體   English   中英

如何為 *ngIf 中聲明的模板調用 @ViewChild?

[英]How to call @ViewChild for a template declared inside a *ngIf?

我在表內動態調用組件。 我正在使用 ViewContainerRef 在模板內動態呈現組件。 但是另一個元素內的模板沒有被填充。 可能是因為在聲明@ViewChild時,另一個 ng-template 不在 DOM 中。

這是組件代碼:

@ViewChild('loadComponent', {static: false, read: ViewContainerRef}) ref;


ngAfterViewChecked(): void {

    const componentFactory = 
    this._componentFactoryResolver.resolveComponentFactory(DynamicComponent);
    const ref = this.ref.createComponent(componentFactory);
    ref.changeDetectorRef.detectChanges();
  }

這是模板代碼:

<table>
...
    <tr *ngFor="let data of dataItems">       

       <td *ngIf="data.isDisplay">        

       <ng-template #loadComponent></ng-template> // this does'nt work  

    </td>

...

那么,一旦動態評估td代碼,如何確保組件在td內呈現?

編輯

通過非靜態獲取所有模板引用,您可以遍歷模板引用並為每個模板創建一個組件,之后您只需將其附加到某個 DOM 元素(模板引用的父級)

@ViewChildren("dynamicTemplateId") private refs: QueryList<"dynamic">;

this.refs.forEach((r: any) => {
  // Create a new instance of the component
  const dynamicComponentRef = componentFactory.create(this.injector);

  // If you don't attach to appRef ng hook cycles won't work inside the component 
  // You can skip adding to application ref but you'll be needing to call .detectChanges() for every changes 
  this.appRef.attachView(dynamicComponentRef.hostView);

  // Append to parentElement since templateRef isn't a element itself
  r.elementRef.nativeElement.parentElement.appendChild(dynamicComponentRef.location.nativeElement);
});

這是一個工作示例: https://stackblitz.com/edit/angular-gmnpku?file=src/app/app.component.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM