如何从“角度材质”对话框获取数据?

时间:2019-07-10 23:55:30

标签: angular user-interface angular-material components user-input

如何从Angular材质对话框中的输入字段中获取数据?

这是我的代码:

TS

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

@Component({
  selector: 'app-test',
  templateUrl: './foo.component.html',
  styleUrls: ['./foo.component.scss']
})

export class SomeComponent implements OnInit {

  name: String;

  constructor(public dialog: MatDialog) { }

  ngOnInit() {
  }

  openDialog(): void {
    const dia = this.dialog.open(SomeDialogComponent, {
      width: "250px",
      data: { name: this.name }
    });

    dia.afterClosed().subscribe(result => {
      console.log("The dialog was closed");
      console.log("Your Name: " + this.name);
      this.name = result;
    });
  }
}

@Component({
  selector: "someDialog",
  templateUrl: "someDialog.html",
  styleUrls: ["someDialog.scss"]
})

export class SomeDialogComponent {

  constructor(public dialog: MatDialogRef<SomeDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) { }

  onNoClick(): void {
    this.dialog.close();
  }
}

对话框HTML

<body>
    <h1 mat-dialog-title>Enter your name</h1>

    <div mat-dialog-content class="contentBox">
        <mat-form-field>
            <input type="text" matInput>
        </mat-form-field>

        <div mat-dialog-actions>
            <button mat-raised-button (click)="onNoClick()">Exit</button>
            <button mat-raised-button (click)="sendData()">Ok</button>
        </div>
    </div>
</body>

我从Angular资料的官方文档https://material.angular.io/components/dialog/overview中获得了此代码,但未按预期工作。


期望

我希望对话框将数据传递回组件而不使用模型,就像我在代码段中输入的那样。

实际

对话框不会将数据传递回组件,而是在登录时返回undefined

1 个答案:

答案 0 :(得分:2)

  1. 您没有将输入值绑定到所需的数据属性
  2. 您没有'sendData()'方法
  3. 最重要的是:在将名称分配结果值之前,您正在记录名称。

将对话框的html代码更新为此:

<body>
<h1 mat-dialog-title>Enter your name</h1>

<div mat-dialog-content class="contentBox">
    <mat-form-field>
        <input [(ngModel)]="data.name" matInput>
    </mat-form-field>

    <div mat-dialog-actions>
        <button mat-raised-button (click)="onNoClick()">Exit</button>
        <button mat-raised-button [mat-dialog-close]="data.name">Ok</button>
    </div>
</div>

它应该像这样工作。