我有一个简单的弹出窗口,显示一 strip 有“确定”按钮以释放它的消息,我想要的是向此弹出窗口添加一个文本字段,用户需要在其中输入一些内容,然后单击“确定”提交他的答案。
目前看起来像这样:
@Component({
selector: 'dialog-component',
template: `<h2>{{title}}</h2>
<p>{{message}}</p>
<button md-button (click)="dialog.close()">OK</button>`
})
export class DialogComponent {
public title: string;
public message: string;
constructor( public dialog: MdDialogRef<DialogComponent>) { }
}
我使用它的方式如下:
public showDialog(message: MessageBoxMessage) {
if (typeof message !== 'undefined') {
let dialogRef: MdDialogRef<DialogComponent> = this._dialog.open(DialogComponent);
dialogRef.componentInstance.title = message.title;
dialogRef.componentInstance.message = message.content;
}
}
如何将其更改为带有文本字段和确定按钮的弹出窗口,以便向我传递文本字段的值?
最佳答案
您可以在对话框中创建EventEmitter
:
@Component({
selector: 'dialog-component',
template: `<h2>{{title}}</h2>
<p>{{message}}</p>
<mat-form-field class="example-full-width">
<input matInput placeholder="Favorite food" #input>
</mat-form-field>
<button mat-button (click)="onOk.emit(input.value); dialog.close()">OK</button>`
})
export class DialogComponent {
public title: string;
public message: string;
onOk = new EventEmitter();
constructor( public dialog: MatDialogRef<ErrorDialogComponent>) { }
}
然后在父组件中订阅它
dialogRef.componentInstance.onOk.subscribe(result => {
this.resultFromDialog = result;
})
<强> Plunker Example
另一种方法是将值传递给 MatDialog.close
方法
(click)="dialog.close(input.value)"
....
dialogRef.afterClosed().subscribe(result => {
this.resultFromDialog = result;
});
<强> Plunker Example
关于html - 带文本字段输入的 Angular 2 对话框弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42789764/