简体   繁体   English

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

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

I am calling a component dynamically inside a table.我在表内动态调用组件。 I am using ViewContainerRef to render the component dynamically inside a template.我正在使用 ViewContainerRef 在模板内动态呈现组件。 But the template that is inside another element, is not being populated.但是另一个元素内的模板没有被填充。 Maybe because while declaring @ViewChild , the other ng-template is not in the DOM.可能是因为在声明@ViewChild时,另一个 ng-template 不在 DOM 中。

Here is the component code:这是组件代码:

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


ngAfterViewChecked(): void {

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

Here is the template code:这是模板代码:

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

       <td *ngIf="data.isDisplay">        

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

    </td>

...

So, how do I make sure that the component is rendered inside the td once the td code is evaluated dynamically?那么,一旦动态评估td代码,如何确保组件在td内呈现?

Edit :编辑

By getting all templateRefs non statically, you could iterate through the template refs and create a single component for every one, after that you only need to attach it to some DOM element (templateRef's parent)通过非静态获取所有模板引用,您可以遍历模板引用并为每个模板创建一个组件,之后您只需将其附加到某个 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);
});

Here's a working example: https://stackblitz.com/edit/angular-gmnpku?file=src/app/app.component.ts这是一个工作示例: 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