4

I am implementing an md-dialag from Material Design on my Angular 4 application. I have currently achieved to pass data into the modal, but have not been successful to retrieve any data entered by the user on the dialog.

This is how I open a dialog:

ShowAddStop() {
    this.general = {fc: this.locationCtrl, fl: this.filteredLocations, selectedNewStop:this.selectedNewStop};
    let dialogRef = this.dialog.open(DialogAddStop,{data:this.general});
    dialogRef.afterClosed().subscribe(result => {
        console.log(result);
    });
}

But for instance, on the dialog I have an input field which I want the user to fill:

<input [(ngModel)]="ShortName">

Where Shortname is a variable on the class from where I called the dialog, it won't change that variable, I think it creates its own scope and that's why it isn't using my class instance variables.

Is there something basic I'm missing on retrieving data back from the dialog?

Multitut
  • 2,089
  • 7
  • 39
  • 63

1 Answers1

4

First, acquire a MdDialogRef<DialogAddStop> reference and a MD_DIALOG_DATA token in the dialog constructor:

constructor(
  @Inject(MD_DIALOG_DATA) private dialogData: any,
  private dialogRef: MdDialogRef<DialogAddStop>
) {}

See also Using MdDialogConfig data on Angular 2 for some explanations regarding MD_DIALOG_DATA.

Create a shortName variable inside the dialog class:

public shortName: string

Set initial value of shortName to the one provided by the parent component:

public ngOnInit(): void {
  this.shortName = this.dialogData['shortName']
}

Create a “saving” handler:

public onSave() {
  this.dialogRef.close(this.shortName)
}

Attach that handler to the Save button:

<button (click)="onSave()" md-button>Save</button>
gsc
  • 1,559
  • 1
  • 13
  • 17
  • Thanks! but how do I get that variable on the class from where I called the dialog? (it works inside the dialog onSave() method by the way) – Multitut Jun 08 '17 at 20:56
  • 1
    Have you tried subscribing to `dialogRef.afterClosed()` and reading its result? – gsc Jun 09 '17 at 07:57