I have a view which holds ng template for MD-Dialog.
<ng-template #template>
<h2 md-dialog-title>{{title}}</h2>
<div md-dialog-content #content></div>
</ng-template>
Where I have to replace #content with a dynamic component.
corresponding component class is,
export class CustomDialogComponent implements OnInit, AfterViewInit {
title: string;
@ViewChild('content', { read: ViewContainerRef }) container;
@ViewChild('template') template: TemplateRef<any>;
constructor(public dialog: MdDialog,
private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnInit() {
}
open(component: any, options: any): void {
this.title = options.title;
console.log(this.container)
const dialogRef = this.dialog.open(this.template, options);
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
this.container.clear();
const comp = this.container.createComponent(componentFactory);
comp.instance.setData(options.data);
}
close() {
this.dialog.closeAll();
}
ngAfterViewInit() {
console.log(this.container)
}
}
But I get undefined for this.container in method open(). Please help.
template inside a template is reachable only when view is initialized, so
after angular 8, when using ViewChild, you can use parameter{static: false}
this way you can have instance of the inside template when view is initialized
@Viewchild('content', {static: false}) innerConttent: TemplateRef<any>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With