【问题标题】:Is there a way to bind to an array of components in angular and render those in the current component using ngFor有没有办法以角度绑定到组件数组并使用 ngFor 渲染当前组件中的组件
【发布时间】:2020-08-23 11:31:46
【问题描述】:

首先,这与以下问题有关:

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

【问题讨论】:

  • 这可能会对您有所帮助:angular.io/guide/built-in-directives#ngfor。还有这个:angular.io/tutorial/toh-pt2
  • 文档并没有真正提到迭代动态组件。它似乎只谈论组件何时被专门键入。但是,这可能吗:
  • 组件数组会是什么样子? Angular 中的组件需要使用 componentFactory 创建。你想要的很可能,但它需要更多的功能。
  • 我不知道组件属性在视图模型上的外观。我看到你可以像这样注入 ViewChildren:@ViewChildren(Item) items:QueryList&lt;Item&gt;; 但是 QueryList 对象有一个通用类型参数(因为我要求任何组件,我不确定它是如何工作的)

标签: angular angular-components


【解决方案1】:

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中处理

应用组件

// 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', 'sister', 'baby'];,它将呈现上面的 3 个组件
  • 如果只是['brother', 'baby'];,它只会渲染BrotherComponentBabyComponent

附上另一个Stackblitz Demo供你参考

【讨论】:

  • 这是我要找的,谢谢你的帮助!
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
相关资源
最近更新 更多