2

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?

8
  • su pregunta no es clara... it creates confusion. would you please make it better? Commented Jan 25, 2016 at 11:44
  • tldr; How do I dynamically insert different components from an array? Commented Jan 25, 2016 at 11:48
  • Do you want to go through json object loop and want to make dynamic components encountered? Commented Jan 25, 2016 at 11:50
  • The json object would be parsed somehow inside my main ReportComponent (doesnt matter how I get it), what I mean is that I don't know what children components I will be inserting beforehand. Commented Jan 25, 2016 at 11:53
  • If you say you don't know what children component you will be inserting, it means you are saying you don't know how @component decorator will be defined for each component. So, I think It doesn't look straight and simple answer. But hopefully you can take a look at DynamicComponentLoader of angular2. But hope somebody else would be able to answer now or later. Commented Jan 25, 2016 at 12:20

1 Answer 1

2

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

Comments

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.