[英]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.我只是评论了它。
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.