ecash
ecash

Reputation: 53

Is there a way to bind to an array of components in angular and render those in the current component using ngFor

To preface, this is related to the following question:

Is there a way to programmatically render a component in Angular?

Is it possible to render dynamic components from an array in the view model? (similar to using the ng-template for a single component from the aforementioned question).

<div *ngFor="let component of components">
    <Do something here to render component>
</div>

I worked with KnockoutJs prior and it was fairly easy to accomplish this with something like the following in the view:

<!-- ko foreach: someArrayOfComponents -->
    <!-- ko component: { componentName: 'some-component', params: someComponentViewModel } --><!-- /ko -->
<!-- /ko -->

Upvotes: 5

Views: 5640

Answers (1)

KShewengger
KShewengger

Reputation: 8269

In ng-template, there's also an equivalent of implementing ngFor. It is through:

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

Attached Stackblitz Demo for your reference.


If you want to render dynamic components inside an array, it's best to handle them in ngSwitchCase

AppComponent

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

<my-parent *ngFor="let component of components"     
           [component]="component">
</my-parent>

ParentComponent (handles the 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>
  • So if the components array value is ['brother', 'sister', 'baby']; it will render the 3 components above
  • if it's just ['brother', 'baby']; it will only render the BrotherComponent and BabyComponent

Attached another Stackblitz Demo for your reference

Upvotes: 4

Related Questions