简体   繁体   中英

Close button of MatDiaLog in Angular get error Cannot read property 'close' of null

I want to create a component with multiple content project in angular 6. It might be

This is the content I passed from the app.component.html :

<popup>
  <button buttonTrigger mat-button><span >Open the popup!</span></button>
  <my-dialog-content content></my-dialog-content>
</popup>

This is the content of the popup.component.html

<div (click)="openDialog()"><ng-content select="[buttonTrigger]" ></ng-content></div>
<ng-template #dialogContent>
  <ng-content select="[content]"></ng-content>
</ng-template>

And this is the content of the dialog content:

<mat-dialog-content>
my-dialog-content works!
</mat-dialog-content>

<mat-dialog-actions align="end">
    <ng-container ngProjectAs="btn-close"><button mat-button color="warn" matDialogClose>Close</button></ng-container>
    <button mat-button color="primary" type="submit" cdkFocusInitial>Submit</button>
</mat-dialog-actions>

This seems work except for the close button:

ERROR TypeError: Cannot read property 'close' of null

This is the link to my source code: https://stackblitz.com/edit/multiple-ngcontent

I don't know if there will be solution or good idea to fix this issue.

Thanks!

You can use dialog.closeAll() , below is the changes you have to do in your code

here's an example

in my-dialog-content.component.html

<mat-dialog-content>
    my-dialog-content works!
</mat-dialog-content>

<mat-dialog-actions align="end">
    <ng-container ngProjectAs="btn-close">
    <button mat-button color="warn" (click)="dialog.closeAll()">Close</button>
  </ng-container>
    <button mat-button color="primary" type="submit" cdkFocusInitial>Submit</button>
</mat-dialog-actions>

and in my-dialog-content.component.ts

import {MatDialog} from '@angular/material';

export class MyDialogContentComponent implements OnInit {

  constructor(public dialog: MatDialog) { }

} 

Updated Stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM