Remember the dymanicComponent we started with? Lets change it code so it will be able to display each of three widgets when a widget type passed as an "input" with its data:
import {Component, ViewContainerRef, ViewChild, Input, ComponentFactoryResolver} from '@angular/core';
import {VERSION} from '@angular/material';
import CompletedTasksComponent from './completed-tasks.component';
import EmailSubscriptionsComponent from './email-subscriptions.component';
import DailySalesComponent from './daily-sales.component';
@Component({
selector: 'dynamic-cmp',
template: `<div>
here some dynamic stuff should happen
<div #dynamicComponentContainer></div>
</div>`,
entryComponents: [
CompletedTasksComponent,
EmailSubscriptionsComponent,
DailySalesComponent
]
})
export class DynamicComponent {
componentRef:any;
@ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {}
@Input() set componentData(data: {component: any, data: any }) {
if (!data) {
return;
}
let factory = this.resolver.resolveComponentFactory(data.component);
this.componentRef = this.dynamicComponentContainer.createComponent(factory);
this.componentRef.instance.data = data.data; // passing data to component through input
}
}
Now the component data and the component type passed to dymanicComponent as input:
<mat-grid-list cols="3" rowHeight="1:1">
<mat-grid-tile *ngFor="let data of componentData">
<dynamic-cmp [componentData]="data"></dynamic-cmp>
</mat-grid-tile>
</mat-grid-list>
Please see my first stackblitz embedd here: