I am trying to insert a template inside a MatDialog reusable component, that is open by a click event.
1) parent component
has the click event code that opens the MatDialog. Here, I try to send a template (which is another component directive) as a data property, to be used in the dialog component
openModal():void{
this.dialog.open(DialogComponent, {
data: {title:"My title",template:"<app-othercomp></app-othercomp>"}
});
}
2) Reusable dialog template It has the ng-template as a placeholder where to insert the template
<div mat-dialog-content>
<ng-template #templatePlaceholder></ng-template>
</div>
3) Reusable dialog component It has the catch of the ng-template reference
@ViewChild('templatePlaceholder', { read: TemplateRef }) templatePlaceholder!: TemplateRef<any>;
and i inject the data in the constructor (and i can access to it) and then i tried to use ngOnInit to make something like this
this.templatePlaceholder = this.data.template;
But it does not work. I was able to make appear the string of the template as just text, but not render it.
I read a lot information on the web:[example 1]
but i am unable to solve this puzzle. Can anyone point me to the right document sample or help me out? Thank you.
UPDATE ONE I tried add this in the parent component that opens the modal:
@Component({
selector: 'app-othercomp',
template: `<div>
ddd
<hr />
</div>`,
})
export class AppMyContentComponent {}
and then...
openModal():void{
this.dialog.open(DialogComponent, {
data: {title:"My title",template:AppMyContentComponent}
});
}
and still no success... but your suggestions are helping me!
UPDATE TWO I created this working example: in the app.component.ts in line 12 is where i need to define the html which is a directive for another component.
CodePudding user response:
Note: Angular has a compiler, it means when you write templates in a component then templates becomes javascript instructions and there is no html markup anymore. so you cannot use dynamic template as <app-othercomp></app-othercomp>
at runtime.
But if you want to pass an angular component as dynamic template you can use @angular/element
package to produce standard web component from it.
createCustomElement(AppOtherComponent)
and then use the template as innerHTML
in dialog
<div mat-dialog-content [innerHTML]="data.template"></div>
CodePudding user response:
I think you want to specify the content of the modal in html instead of ts
<ng-template #modalTemplate>
<app-othercomp></app-othercomp>
</ng-template>
And use it in typescript:
@ViewChild('modalTemplate') modalTemplate!: TemplateRef<any>;
openModal():void{
this.dialog.open(DialogComponent, {
// data: {title:"My title",template:"<app-othercomp></app-othercomp>"}
{ data: { title: 'My title', template: this.modalTemplate } }
});
}
Edit
Here's a StackBlitz where the template is specified in the component calling the modal, as you state