为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

跃然一笑 2021-11-18 17:07:18
我在表内动态调用一个组件。我正在使用 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代码被动态评估,我如何确保组件在内部呈现?
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

编辑:


通过非静态获取所有 templateRefs,您可以遍历模板 refs 并为每个组件创建一个组件,之后您只需要将其附加到某个 DOM 元素(templateRef 的父元素)


@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


查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 186 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信