Issue
I want to render components in a list, but I cannot do this statically. Based on user import I can determine which components I have to show. The problem also is that depending on input inside those components the list can change too
Right now I have everything hardcoded in HTML with a lot of *ngIfs. This worked well but as the complexity of my app increased this approach seems to becoming hard to maintain.
Anyway, my solution is to render the components dynamically, so I only need to create a list of components I would like to render.
Here is a nice article which describes how to dynamically add one component. You create a template
<template #alertContainer></template>
to which you add the dynamic component
const factory: ComponentFactory = this.resolver.resolveComponentFactory(AlertComponent);
this.componentRef: ComponentRef = this.container.createComponent(factory);
However, in my case I have a list
<ol>
<li *ngFor="let component of components">
<template ........</template>
</li>
</ol>
So how can I create a list in this case (I also need to bind to @Inputs and @outputs)?
Solution
I've been testing what I mentioned in the comments. This solution is probably what you were looking for. Also I've been playing with it and I've implemented a couple things like event emitting between rendered components, input data to the rendered components and more.
Basically you have a module called ComponentLoaderModule that has a component called ComponentLoader. This component is encharged of rendering components and dealing with the events. Then you have a wrapper component called entry-component, where we spawn the ComponentLoader as many times we need.
From app.component we call the entry-component with all the components we want.
Since it is too big to fit in here, I drop this link where you can take a deep look into it: https://stackblitz.com/edit/angular-ivy-cfyaca?file=src/app/entry-component/entry-component.component.ts
EDIT: This is just a 20 min game in stackblitz, its basic and could be potentially upgraded. It is just a showcase or a start point to build on top.
Answered By - Osakr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.