【问题标题】:How to get data from Angular material dialog?如何从 Angular 材质对话框中获取数据?
【发布时间】:2019-11-20 15:07:24
【问题描述】:

如何从 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 中获得了这段代码,但它没有按预期工作。


预期

我希望对话框在不使用模型的情况下将数据传回组件,就像我在 sn-p 中放入的变量一样。

实际

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

【问题讨论】:

  • 你需要将Dialog的字段绑定到构造函数中的data。使用[(ngModel)] 或[(value)] 大多数时候你的data 将是一个对象(因此使用多个字段更容易)所以你的输入字段应该是数据的属性(如data.inputField)
  • 我明白了,你能提供这两种情况的代码示例吗?

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


【解决方案1】:
  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>

它应该像那样工作。

【讨论】:

  • 我有一个错误:Can't bind to 'ngModel' since it isn't a known property of 'input'.
  • logger还在控制台输出undefined,数据依然没有传输。
  • 嗯,奇怪。我发现它在我第一次输入内容时给了我undefined。但是当我再次打开它时,数据被保存了,我再次按下确定,这次它正在发送数据。
  • 对不起,我的错。它是第一次发送数据,只是console.log 似乎第二次捕获它。现在一切正常,谢谢!
猜你喜欢
  • 2019-06-22
  • 2020-12-30
  • 2020-10-02
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
相关资源
最近更新 更多