问题描述
首先,这与以下问题有关:
Is there a way to programmatically render a component in Angular?
是否可以从视图模型中的数组渲染动态组件? (类似于将ng-template用于上述问题中的单个组件)。
<div *ngFor="let component of components">
<Do something here to render component>
</div>
我以前使用过KnockoutJs,并且在视图中使用类似以下内容的方法很容易做到这一点:
<!-- ko foreach: someArrayOfComponents -->
<!-- ko component: { componentName: 'some-component',params: someComponentviewmodel } --><!-- /ko -->
<!-- /ko -->
解决方法
在ng-template
中,也等效于实现ngFor
。
通过以下方式完成:
<ng-template ngFor // Indication of your ngFor loop
[ngForOf]="components" // Your list
let-component // Your component from components
let-i="index"> // Your index
...
</ng-template>
附加了 Stackblitz Demo 供您参考。
如果要在数组内渲染动态组件,最好在ngSwitchCase
中处理它们
AppComponent
// components = ['brother','sister','baby'];
<my-parent *ngFor="let component of components"
[component]="component">
</my-parent>
ParentComponent(处理ngSwitch)
<div>
<div [ngSwitch]="component"> // Whatever value passed inside the @Input() component,it will render the component based on the conditions or cases below
<my-brother *ngSwitchCase="'brother'"></my-brother> // BrotherComponent
<my-sister *ngSwitchCase="'sister'"></my-sister> // SisterComponent
<my-baby *ngSwitchCase="'baby'"></my-baby> // BabyComponent
</div>
</div>
- 因此,如果
components
数组值为['brother','baby'];
,它将呈现上面的3个分量 - 如果只是
['brother','baby'];
,它将仅呈现BrotherComponent
和BabyComponent
另附了 Stackblitz Demo 供您参考