首页 > 解决方案 > 如何在角度材料中将我们自己的功能分配给 MatDialog

问题描述

我正在使用angular material实现 Popup/Dialog 。有内置功能 openDialog()打开对话框,我想把它改成我的function

这是我的DashboardComponent

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MymodalComponent } from '../modals/mymodal/mymodal.component';   

constructor(public dialog: MatDialog) { }

openDialog(): void {
const dialogRef = this.dialog.open(LastseenDevicesComponent, {
    width: '80%',
    height:'80%',
    panelClass: 'my-dialog',
    disableClose: true ,
  data: { name: "this.name", animal: "this.city" }
});

的html文件DashboardComponent

<ol>
  <li>
    <mat-form-field>
      <mat-label>Where do you stay?</mat-label>
      <input matInput [(ngModel)]="name">
    </mat-form-field>
  </li>
  <li>
    <button mat-raised-button (click)="openDialog()">Pick city or food</button>
  </li>
  <li *ngIf="city">
    You chose: <i>{{city}}</i>
  </li>
  <li *ngIf="food_from_modal">
    I love {{food_from_modal}}
  </li>
</ol> 

这是对话框组件LastseenDevicesComponent

<div md-dialog-content>
     <button class="close" mat-button (click)="onNoClick()">
        <mat-icon>close</mat-icon>
    </button>
    
    <p>What's your favorite city?</p>
    <mat-form-field>
        <mat-label>Favorite City</mat-label>
        <input matInput [(ngModel)]="data.city">
    </mat-form-field>

</div>
<div mat-dialog-actions>
    <button id="matbuttonClose" mat-button [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>
  </div>
</html>

这就是我想要制作它的方式,而不是openDialog(): void我想用我的代码替换它DashboardComponent

//This getting called when I click on my chart bar
function lastSeenDevice() {

const dialogRef = this.dialog.open(LastseenDevicesComponent, {
    width: '80%',
    height:'80%',
    panelClass: 'my-dialog',
    disableClose: true ,
  data: { name: this.name, animal: this.city }
});

如果我这样做会出错

ERROR TypeError: Cannot read property 'open' of undefined
at Chart.lastSeenDevice (dashboard.component.ts:509)
at Chart.handleEvent (Chart.js:10213)
at Chart.eventHandler (Chart.js:10150)
at listener (Chart.js:10083)
at HTMLCanvasElement.proxies.<computed> (Chart.js:7813)
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:39680)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:465)

标签: angularangular-material

解决方案


看到这个错误的原因:

Cannot read property 'open' of undefined

你的 lastSeenDevice() 函数中 this.dialog.open 中的“this”是指与类不同的上下文吗?

所以要解决这个问题:在你的仪表板组件中确保你有 lastSeenDevice() 函数,并删除“function”关键字以使其成为类方法,因此将“this”作为仪表板类的上下文。

所以从:

function lastSeenDevice() { ... your code here . . .}

至:

lastSeenDevice() { ... your code here ... }

还要确保:

 <button mat-raised-button (click)="openDialog()">

您将其更改为:

 <button mat-raised-button (click)="lastSeenDevice()">

推荐阅读