html - 带文本字段输入的 Angular 2 对话框弹出

标签 html angular typescript

我有一个简单的弹出窗口,显示一 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/

相关文章:

html - 如何使用 CSS 将图像定位在最右侧?

javascript - CSS:隐藏/未隐藏元素的动态边距

angular - 如何在 Angular 2 中为多个子组件提供单独的服务实例

javascript - 尽管导入模块并包含 CUSTOM_ELEMENTS_SCHEMA 架构,但组件不是已知元素

javascript - 如何检查所有参数是否相同并返回字符串

javascript - 如何在 jQuery 中获取 parent 的特定下一个和 previous sibling 姐妹的 child ?

html - 如何删除聚焦按钮文本周围的白色虚线边框

html - Angular 8 通过只有 id 从输入中获取值

apache - 在 Apache Tomcat 404 深度链接问题上部署 Angular 应用程序

javascript - angular2 中 angular.isString() 的替代方法是什么?