Our team had interesting case with material dialog.
We are working on common components, that are used by other teams and our goal is to simplify the development process.
The problem was that the material dialogue does not support transclude (<ng-content>).
To solve the problem created a separate DialogContentComponent, that is passed into
this.dialogRef = this.dialog.open(DialogContentComponent, {disableClose: true})
that is inside of DialogComponent.
DialogContentComponent has a template of the dialog, which should be everywhere the same, and in DialogComponent template we have only this:
<ng-template #template>
<ng-content></ng-content>
</ng-template>
So in this case DialogComponent has access to the content through
@ViewChild('template') public transcludeTemplate: TemplateRef<any>;
and passes it to DialogContentComponent through the component instance after it was opened:
this.dialogRef.componentInstance.template = this.transcludeTemplate;
On the other hand, DialogContentComponent has a place to insert a template
<div #view></div>
that we could access by
@ViewChild('view', { read: ViewContainerRef }) public view: ViewContainerRef;
and whenever content changes, we call two methods:
this.view.clear();
this.view.createEmbeddedView(this.template);
As a result, we can reuse our component like this:
<dialog [show]="showDialog"
(close)="onClose()"
[caption]="caption"
[buttons]="dialogButtons">
<div class="demo-content">
<p>Transcluded template</p>
</div>
</dialog>
and, in addition, we can transfer the template separately to the binding, in this form:
<dialog [show]="showDialog"
(close)="onClose()"
[caption]="caption"
[buttons]="dialogButtons"
[template]="testtemplate">
</dialog>
<ng-template #testtemplate>
<div class="demo-content">
<p>Transcluded template</p>
</div>
</ng-template>
In order to achieve this, we add an input like this:
@Input() public template: TemplateRef<any>;
and use it in the code instead of this.transcludeTemplate
Hope this will help those who are faced with the problem of transferring dynamic content to the material dialog.