0

I want to create a component in Angular2 which will show a table with some data(lets assume sales data of different product P1 and P2). Along with the table I want to allow user to choose option between different type of graphs and based on the graph selection I want to show the graph of shown data in a container below the data table.

I have created a component(lets call it Main) which have as one component, A radio group showing graph type. Now for 10 different graph type, and I have created 10 different graph component for these 10 types.

Approach: I can put all ten component in Main component and based on user selection I show the respective graph component. But this approach would be too costly since Main component shadow dom will have all the graph component. It also present problem If I allow user to select from a range of time and update the shown graph using binding as it will result in updating other graph which are not being shown.

Is there any approach where I can put a generic container in Main component and inject a list of graph component in main component and based on user selection I put the selected graph component in that container. Putting in the container should not disrupt binding.

Just to summarize, I want to find a way to dynamically put the component in a another component. Ideally in Composite Design Pattern it should be fairly easy to determine component in runtime. I am not able to figure that out in angular 2.

Badal Singh
  • 918
  • 1
  • 6
  • 13
  • Check the dynamic component loader https://angular.io/docs/js/latest/api/core/DynamicComponentLoader-class.html – Angular University Jul 24 '15 at 21:44
  • Thanks, It might work for me, I will try to share a sample :) – Badal Singh Jul 27 '15 at 18:36
  • `ViewContainerRef.createComponent` replaced `DynamicComponentLoader` a long time ago. See http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 for an example. – Günter Zöchbauer Feb 20 '17 at 18:05

1 Answers1

1

Use DynamicComponentLoader For an example of a dynamically loaded component, see this plnkr. The key is this.dcl.loadNextToLocation(Widget1, this.insertPoint); and using System.import in the code to lazy load the component. Although I'll point out that components aren't loaded into the shadow DOM until they are instantiated*, so lazy loading may not be necessary.

loadNextToLocation is one of three methods in DynamicComponentLoader you can use, depending on how and where you want the component injected. Note that loadAsRoot has an issue (current as of 2.0.0-beta.7) that prevents it loading properly in all cases. See this plnkr for details.

Blue
  • 728
  • 8
  • 9