带有文本字段输入的Angular 2对话框弹出窗口

时间:2017-03-14 15:13:26

标签: html5 angular typescript

我有一个简单的弹出窗口,显示带有确定按钮的消息以释放它,我想要的是在此弹出窗口中添加一个文本字段,用户需要在其中键入内容并单击确定以提交他的答案。< / p>

目前它看起来像这样:

@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;
    }
  }

如何更改它以使用带有text-field的弹出窗口和ok按钮向我传递text-field的值?

2 个答案:

答案 0 :(得分:2)

您可以在对话框中创建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

答案 1 :(得分:0)

您可以将答案绑定到这样的模型:

@Component({
  selector: 'dialog-component',
  template: `<h2>{{title}}</h2>
      <p>{{message}}</p>
      <input type="text" name="data" [(ngModel)]="data">
      <button md-button (click)="dialog.close()">OK</button>`
})
export class DialogComponent {

  public title: string;
  public message: string;
  data: string;

  constructor( public dialog: MdDialogRef<ErrorDialogComponent>) { }
}

然后将(click)绑定到发送数据的函数。