如何为 *ngIf 中声明的模板调用@ViewChild?

我在表内动态调用一个组件。我正在使用 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代码被动态评估,我如何确保组件在内部呈现?


跃然一笑
浏览 187回答 1
1回答

慕神8447489

编辑:通过非静态获取所有 templateRefs,您可以遍历模板 refs 并为每个组件创建一个组件,之后您只需要将其附加到某个 DOM 元素(templateRef 的父元素)@ViewChildren("dynamicTemplateId") private refs: QueryList<"dynamic">;this.refs.forEach((r: any) => {&nbsp; // Create a new instance of the component&nbsp; const dynamicComponentRef = componentFactory.create(this.injector);&nbsp; // If you don't attach to appRef ng hook cycles won't work inside the component&nbsp;&nbsp; // You can skip adding to application ref but you'll be needing to call .detectChanges() for every changes&nbsp;&nbsp; this.appRef.attachView(dynamicComponentRef.hostView);&nbsp; // Append to parentElement since templateRef isn't a element itself&nbsp; r.elementRef.nativeElement.parentElement.appendChild(dynamicComponentRef.location.nativeElement);});这是一个工作示例:https : //stackblitz.com/edit/angular-gmnpku?file=src/app/app.component.ts
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript