简体   繁体   English

在 Angular 9 中动态加载 *ngFor 内部的组件

[英]Dynamically load components inside *ngFor in Angular 9

I studied the code available on angular.io , and I replicated it in my scenario with a mat-tab-group .我研究了 angular.io 上可用的代码,并使用mat-tab-group在我的场景中复制了它。 However, I would like to be able to use the ad-host directive inside a *ngFor .但是,我希望能够在*ngFor中使用 ad-host 指令。 I tried it, and the directive is always undefined .我试过了,指令总是undefined

I searched here and, while there are several questions addressing this problem, I found no clear example on how to do this.我在这里搜索,虽然有几个问题可以解决这个问题,但我没有找到关于如何做到这一点的明确示例。 The idea is that I have a mat-tab-group composed of several mat-tabs , which are loaded through a *ngFor directive.这个想法是我有一个mat-tab-group由几个mat-tabs组成,它们是通过*ngFor指令加载的。 In each tab I would like to show a different component according to the selected index.在每个选项卡中,我想根据所选索引显示不同的组件。 Is there any way to achieve this?有什么办法可以做到这一点?

Here is my modified stackblitz: as you can see it literally says this.adHost is undefined in the console.是我修改后的 stackblitz:正如你所看到的,它的字面意思是this.adHost is undefined的。

You need to change the way you get a reference to your adHost .您需要更改获取adHost引用的方式。

@ViewChild(AdDirective, {static: false}) adHost: AdDirective;

It needs to be static: false (see documentation ) because it's rendered dynamically by mat-tab , so it's not always in the template.它需要是static: false (参见文档),因为它是由mat-tab动态呈现的,所以它并不总是在模板中。

And don't call loadComponents in ngOnInit , since the view has not been rendered yet, so adHost will be undefined.并且不要在ngOnInit中调用loadComponents ,因为视图还没有被渲染,所以adHost将是未定义的。 Use ngAfterViewInit for instance.例如使用ngAfterViewInit I just commented it.我只是评论了它。

Corrected stackblitz更正了堆栈闪电战

Edit编辑

Following your clarifications, I changed quite a lot of things (removed your setInterval , used @ViewChildren instead of ViewChild , use ngOnChanges to know when to render the data, etc.).根据您的说明,我更改了很多内容(删除了您的setInterval ,使用@ViewChildren而不是ViewChild ,使用ngOnChanges知道何时呈现数据等)。

Here is the stackblitz example这是stackblitz示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM