有没有办法绑定到 Angular 中的组件数组并使用 ngFor 渲染当前组件中的组件

eca*_*ash 5 angular-components angular

作为序言,这与以下问题有关:

有没有办法以编程方式在 Angular 中渲染组件?

是否可以从视图模型中的数组渲染动态组件?(类似于对上述问题中的单个组件使用 ng-template )。

<div *ngFor="let component of components">
    <Do something here to render component>
</div>
Run Code Online (Sandbox Code Playgroud)

我之前使用过 KnockoutJs,通过视图中的以下内容可以很容易地完成此任务:

<!-- ko foreach: someArrayOfComponents -->
    <!-- ko component: { componentName: 'some-component', params: someComponentViewModel } --><!-- /ko -->
<!-- /ko -->
Run Code Online (Sandbox Code Playgroud)

KSh*_*ger 4

在 中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>

Run Code Online (Sandbox Code Playgroud)

附上Stackblitz Demo供大家参考。


如果你想在数组中渲染动态组件,最好在ngSwitchCase

应用组件

// components = ['brother', 'sister', 'baby'];

<my-parent *ngFor="let component of components"     
           [component]="component">
</my-parent>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)
  • 因此,如果components数组值为 ,['brother', 'sister', 'baby'];它将渲染上面的 3 个组件
  • 如果它只是['brother', 'baby'];它只会渲染BrotherComponentBabyComponent

附上另一个Stackblitz Demo供您参考