How do you get data from an input field inside an Angular material dialog?
This is my code:
TS
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
@Component({
selector: 'app-test',
templateUrl: './foo.component.html',
styleUrls: ['./foo.component.scss']
})
export class SomeComponent implements OnInit {
name: String;
constructor(public dialog: MatDialog) { }
ngOnInit() {
}
openDialog(): void {
const dia = this.dialog.open(SomeDialogComponent, {
width: "250px",
data: { name: this.name }
});
dia.afterClosed().subscribe(result => {
console.log("The dialog was closed");
console.log("Your Name: " + this.name);
this.name = result;
});
}
}
@Component({
selector: "someDialog",
templateUrl: "someDialog.html",
styleUrls: ["someDialog.scss"]
})
export class SomeDialogComponent {
constructor(public dialog: MatDialogRef<SomeDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) { }
onNoClick(): void {
this.dialog.close();
}
}
Dialog HTML
<body>
<h1 mat-dialog-title>Enter your name</h1>
<div mat-dialog-content class="contentBox">
<mat-form-field>
<input type="text" matInput>
</mat-form-field>
<div mat-dialog-actions>
<button mat-raised-button (click)="onNoClick()">Exit</button>
<button mat-raised-button (click)="sendData()">Ok</button>
</div>
</div>
</body>
I got this code from the Angular material's official documentation, https://material.angular.io/components/dialog/overview, but it is not working as expected.
Expected
I want the dialog to pass the data back the component without the use of a model, just a variable like I have put in my snippet.
Actual
The dialog does not pass the data back to the component and returns undefined
instead when logged.
data
in the constructor. Using[(ngModel)]
or[(value)]
Most of the time yourdata
will be an object (so it's easier to work with multiple fields) so your input field should be a property of data (likedata.inputField
) – Shonna