Chris K
Chris K

Reputation: 928

Insert component dynamically in Angular 2 knowing component string name

How to insert component in Angular 2+ dynamically in this situation?

<div *ngFor="let component of components">

</div>

Where components is an array of strings, one string is a single component name. How to do this in such a situation? I want all components from array to be shown.

This is an example array of components:

components: ['app-item-search-sidebar','app-item-list','app-item-create','app-item-change'];

Upvotes: 2

Views: 61

Answers (1)

Prachi
Prachi

Reputation: 3574

You can use ngSwitch:

<div *ngFor="let component of components" [ngSwitch]="component">
    <div *ngSwitchCase="'child-component-one'">
         <child-component-one></child-component-one>
    </div>
    <div *ngSwitchCase="'child-component-two'">
         <child-component-two></child-component-two>
    </div>
    <div *ngSwitchCase="'child-component-three'">
         <child-component-three></child-component-three>
    </div>
    ... //append other component selectors
</div>

Upvotes: 1

Related Questions