如何从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
。
答案 0 :(得分:2)
将对话框的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>
它应该像这样工作。