DEV Community

Discussion on: ViewChild, ViewChildren and ContentChild, ContentChildren are undefined in Angular Material Dialog

Collapse
 
akotech profile image
akotech

Hi Ram,

You cannot query for a reference defined in other component template, since each template is a black box to its relatives.
You have to add the following in the ModalComponent template <ng-template #template><ng-content></ng-content></ng-template> to capture the projected content you have defined inside the <app-modal> in the dashboard.

modal.component.ts

@Component({
  selector: 'app-modal',
  template: `
    <ng-template #template><ng-content></ng-content></ng-template>
    <button mat-raised-button (click)="openDialog()">{{ btnText }}</button>
  `,
   styleUrls: ['./modal.component.scss']
 })
export class ModalComponent {
  ...
  @ViewChild('template') template: TemplateRef<any>;
  ...
}
Enter fullscreen mode Exit fullscreen mode

Then you can pass the templateRef in the dialog data and print the data.template content in the modal-dialog component using a template-outlet like <ng-container *ngTemplateOutlet="data.template"></ng-container>

modal-dialog.component.html

<section>
    ...
    <div mat-dialog-content>
        <ng-container *ngTemplateOutlet="data.template"></ng-container>
    </div>
    ...
</section>
Enter fullscreen mode Exit fullscreen mode

Cheers