Dynamically load a component inside a Material MatDialog
There are different options:
1) Built-in structural directive ngComponentOutlet
<ng-container *ngComponentOutlet="data.component"></ng-container>
Example
2) Using angular material cdk. More precisely you can use PortalModule
from secondary entry point @angular/cdk/portal
dialog.component.ts
import { ComponentPortal } from '@angular/cdk/portal';
@Component({...})
export class DialogDialog {
portal: ComponentPortal<any>;
constructor(...
@Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
this.portal = new ComponentPortal(this.data.component);
}
dialog.component.html
<ng-template [cdkPortalOutlet]="portal"></ng-template>
Example
3) Using Angular low-level API
dialog.component.ts
@Component({...})
export class DialogDialog {
@ViewChild('target', { read: ViewContainerRef }) vcRef: ViewContainerRef;
componentRef: ComponentRef<any>;
constructor(
...
private resolver: ComponentFactoryResolver,
@Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
const factory = this.resolver.resolveComponentFactory(this.data.component);
this.componentRef = this.vcRef.createComponent(factory);
}
ngOnDestroy() {
if (this.componentRef) {
this.componentRef.destroy();
}
}
}
dialog.component.html
<ng-template #target></ng-template>
Example