I have been exploring Angular Dynamic component loader and still not able to get that, when exactly do I need to use this.
Current Scenario: I am getting data of widgets as array of objects. On the basis of each array element I am trying to create a component.
<div *ngFor="let widget of widgets">
<span *ngIf="widget.name=='circle'">
<circle-widget [model]="widget"></circle-widget>
</span>
<span *ngIf="widget.name=='numeric'">
<numeric-widget [model]="widget"></numeric-widget>
</span>
</div>
Same thing I can achieve using dynamic component loader.
<div *ngFor="let widget of widgets">
<dynamic-comp-loader [model]="widget"></dynamic-comp-loader>
</div>
DynamicCompLoader.ts
@Component({
selector: 'dynamic-comp-loader',
templateUrl: './dynamic-comp-loader.component.html',
styleUrls: ['./dynamic-comp-loader.component.scss'],
})
ngOnInit(){
const componentClass = this.getComponentClass(this.model.compName);
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentClass.component);
const viewContainerRef = this.appDynamicCompLoader.viewContainerRef;
viewContainerRef.clear();
if (this.componentRef) {
this.componentRef.destroy();
}
this.componentRef = viewContainerRef.createComponent(componentFactory);
}
Both the cases are working fine and rendering respective components, but I need to understand:-
- When should we use dynamic component loader?
- Is there any performance issue in using either of them?
- Which is the best way to render components on the basis of Iterating elements from array?