JohnBigs
JohnBigs

Reputation: 2811

Angular 2 dialog popup with text field input

I have a simple popup that shows a message with OK button to release it, what I want is to add to this popup a text field that the user will need to type something in it and click OK to submit his answer.

currently it looks like this:

@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>) { }
}

and im using it like:

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

how can I change it to have a popup with text-field and ok button tht pass me the value of the text-field?

Upvotes: 2

Views: 15376

Answers (2)

yurzui
yurzui

Reputation: 214067

You can create EventEmitter in your dialog:

@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>) { }
}

then subscribe to it in parent component

dialogRef.componentInstance.onOk.subscribe(result => {
  this.resultFromDialog = result;
})

Plunker Example

Another way is passing value to MatDialog.close method

(click)="dialog.close(input.value)"
....

dialogRef.afterClosed().subscribe(result => {
  this.resultFromDialog = result;
});

Plunker Example

Upvotes: 2

YounesM
YounesM

Reputation: 2317

You can bind the answer to a model like this :

@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>) { }
}

And then bind the (click) to a function that sends your data.

Upvotes: 0

Related Questions