简体   繁体   中英

Loading dynamic components based on user input in angular 5+

I have an application where a user makes a decision on one page (I'm using cdk stepper), when they get to the next page, I want to dynamically load different components based on what the user selected.

Think of the choices as different form components, and the next page will display one to many of these based on those choices. I don't want to just use ngIf in the html because there will potentially 100+ of these forms, so I want each selection a user makes to have a variable (metadata) associated with it, which can be used to dynamically load any number of components on the next screen.

I looked at CDK Portal for this but I'm wondering if there's a better solution. If there isn't, I'm not 100% sure on how CDK Portal would work for this, every form I think would have to extend some base component. I believe the typescript would be set up to load the components into the portal host. Let me know if anyone has suggestions or questions on this.

Basically, you still need to put the if/else logic elsewhere to make it work. My first approach to this problem is to make a table of selection components with two columns, component's name, and a Boolean to know it is selected:

[(A, false), (B, false)]

You still need to put every components for next step into HTML file, like this:

<a *ngIf="isComponentSelection(a)"></a>
<b *ngIf="isComponentSelection(b)"></b>

The logic inside isComponentSelection is to know this component should be displayed or not, it will check with the table we made above.

In the first board, you just need to bind into the table a list of checkbox with the name of components you have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM