Search code examples
inheritancedynamiccomponentsangularcomposition

Insert different Angular2 components programmatically


I want to programmatically generate a report composed by multiple distinct components from a JSON file like:

{
    components: [UserStatsComponent, ActivityChartComponent, NetworkGraphComponent]
}

I found this: Angular2: Creating child components programmatically but my use case differs in that I need to represent different types of components, so I can't use a ngFor in my template because not every component have the same directive.

I'm new to Angular2 so I don't really know how to approach this: First I thought about component inheritance but looks like angular2 annotations are not inherited when extending a component's class. Don't know how to solve this using composition either.

Heard something about the content tag but don't really know if it's relevant to this use case.

tldr; How do I dynamically insert different components from an array?


Solution

  • To insert components dynamically use the DynamicComponentLoader

    @Component({
      selector: 'child-component',
      template: 'Child'
    })
    class ChildComponent {
    }
    @Component({
      selector: 'my-app',
      template: 'Parent (<child id="child"></child>)'
    })
    class MyApp {
      constructor(dcl: DynamicComponentLoader, injector: Injector) {
        dcl.loadAsRoot(ChildComponent, '#child', injector);
      }
    }