【发布时间】: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