【问题标题】:Close button of MatDiaLog in Angular get error Cannot read property 'close' of nullAngular 中 MatDiaLog 的关闭按钮获取错误无法读取 null 的属性“关闭”
【发布时间】:2018-09-25 03:40:28
【问题描述】:

我想在 Angular 6 中创建一个具有多个内容项目的组件。它可能是

这是我从app.component.html传递过来的内容:

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

这是popup.component.html的内容

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

这是对话内容的内容:

<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>

这似乎工作除了关闭按钮:

ERROR TypeError: Cannot read property 'close' of null

这是我的源代码的链接:https://stackblitz.com/edit/multiple-ngcontent

我不知道是否会有解决此问题的解决方案或好主意。

谢谢!

【问题讨论】:

    标签: angular angular-material dialog


    【解决方案1】:

    您可以使用dialog.closeAll(),以下是您必须在代码中进行的更改

    这是一个例子

    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>
    

    my-dialog-content.component.ts

    import {MatDialog} from '@angular/material';
    
    export class MyDialogContentComponent implements OnInit {
    
      constructor(public dialog: MatDialog) { }
    
    } 
    

    更新Stackblitz

    【讨论】:

    • 嗨,@vuquanghoang
    • 我还有一个问题:是否可以使用@Output 将my-dialog-content.component.html 的事件冒泡到app.component.html 中?
    • 是的,你可以使用输出...看到这个stackblitz.com/edit/multiple-ngcontent-ahendp?file=src/app/…
    • 哇。我认为这是不可能的,因为中间组件会弹出。事实证明我错了。非常感谢!!!
    猜你喜欢
    • 2022-06-29
    • 2023-03-10
    • 2016-01-14
    • 2018-05-05
    • 1970-01-01
    • 2021-08-31
    • 2017-07-08
    • 1970-01-01
    • 2020-09-01
    相关资源
    最近更新 更多