2

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'];
2
  • You already have it explained in the documentation. You can use ViewContainerRef, and decorators such as @ContentChild to do so. But without an actual array I can't provide more help. Commented Jul 6, 2018 at 11:12
  • @mutantkeyboard I have added the array Commented Jul 6, 2018 at 11:18

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

5 Comments

in this situation I can't, because components is also dynamic, and I don't know whats inside, is there other option?
what all variation you would be having? Please add more code.
So the component list is dynamic right? What you need is dynamic component loading.
Right, and even in the dynamic component loading, you need to have a certain number of components in your application ready, then only it will render. You can render a component dynamically, but you cannot create a component dynamically.
@Prachi I have those components ready, I just don't know how to insert them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.