Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from Angular material dialog?

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.

like image 576
Compiler v2 Avatar asked Jun 28 '26 15:06

Compiler v2


1 Answers

  1. you are not binding the input value to the data attribute you want
  2. you don't have a 'sendData()' method
  3. most importantly: you are logging the name before assigning the result value to it.

Update your dialog html code to this:

<body>
<h1 mat-dialog-title>Enter your name</h1>

<div mat-dialog-content class="contentBox">
    <mat-form-field>
        <input [(ngModel)]="data.name" matInput>
    </mat-form-field>

    <div mat-dialog-actions>
        <button mat-raised-button (click)="onNoClick()">Exit</button>
        <button mat-raised-button [mat-dialog-close]="data.name">Ok</button>
    </div>
</div>

It should work like that.

like image 145
Green Avatar answered Jun 30 '26 07:06

Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!