【问题标题】:How to call @ViewChild for a template declared inside a *ngIf?如何为 *ngIf 中声明的模板调用 @ViewChild?
【发布时间】:2019-10-12 18:21:57
【问题描述】:

我在表格内动态调用组件。我正在使用 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 内呈现?

【问题讨论】:

标签: javascript angular components


【解决方案1】:

编辑

通过非静态获取所有模板引用,您可以遍历模板引用并为每个模板创建一个组件,之后您只需将其附加到某个 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

【讨论】:

  • 我认为有一个混淆,我编辑了我的问题,我要加载的模板在 td 内。无论如何,我使用了 '@ViewChildren` 并以某种方式使其工作,但仍然只有第一个元素获得模板而不是其他元素,我无法弄清楚为什么 stackblitz.com/edit/angular-rsxvbt
  • @testsys123 我的错,没有正确理解它正在运行:stackblitz.com/edit/angular-gmnpku?file=src/app/…
  • 非常感谢!通过使用elementRef.nativeElement', can I get template variable value which I will set in html ex: data.Name`?
猜你喜欢
  • 2017-01-14
  • 2022-11-14
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多