Ravi Samanthapudi Ravi Samanthapudi - 5 months ago 39
TypeScript Question

angular 2 - how to import / inject a component during runtime

Let's say that there are two views of product, and I want to show one of those views based on user preferences.

I am thinking to have two views

maintained at two different folders and after user logged in, I want to import from a folder based on how the user prefers to view the product.

Folder 1
----MyProductComponent //exports MyProductComponent with selector <my-product></my-product>
Folder 2
----MyProductComponent //exports MyProductComponent with selector <my-product></my-product>
----App.Component // here I would like to import the component at runtime from either folder 1 / 2 based on user preferences

Please share your insights on this. Are there any alternatives if this cannot be achieved at the component level (ex: at routing level).


Why not just have an *ngIf on two elements that will swap based on the users preference?

<my-product1 *ngIf="userPref1"></my-product1>
<my-product2 *ngIf="!userPref1"></my-product2>

Where userPref1 is a variable (or function) located on App.Component that gets set by user input.

Then the user can state their preference and the application will swap the views based upon their input and you no longer need to deal with importing at run-time.