如何从 Angular 材质对话框获取数据?

Com*_* v2 7 user-interface components user-input angular-material angular

如何从 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

对话框 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>
Run Code Online (Sandbox Code Playgroud)

我从 Angular 材料的官方文档https://material.angular.io/components/dialog/overview获得了这段代码,但它没有按预期工作。


预期的

我希望对话框将数据传递回组件,而不使用模型,只需使用我在代码片段中放入的变量即可。

实际的

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

Gre*_*een 6

  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>
Run Code Online (Sandbox Code Playgroud)

它应该像那样工作。