0

I have a problem I need to pass an object to a mat-dialog. When I consult the value of the object, it is shown with all its properties, the problem occurs when I need to access the properties, they are shown as undefined.

Main Component:

EditDialog(nameInput: String, emailInput: String) {
    const dialogInstance = this.dialog.open(EditDialogComponent,
      {
        width: "40%",
        disableClose: true,
        data: { person: {name: nameInput, email: emailInput } }
      }      
      );
  }

Dialog Component:

constructor(private _formBuilder: FormBuilder,
            @Inject(MAT_DIALOG_DATA) private person: any
            ) { 
                console.log(this.person); <-- show object data
                console.log(this.person.name); <-- show undefined                
              }

Thanks any help

kian
  • 1,449
  • 2
  • 13
  • 21
Andrés
  • 43
  • 5
  • the person object that you're displaying, has a property named `name` which is not `undefined`? – Dorin Baba Aug 21 '21 at 21:55
  • yes the person object shows the correct values ​​in console: person: { name: "Andres", email: "algo@mail.com" } – Andrés Aug 21 '21 at 22:05
  • For this kind of scenario , you have to resolve the issues step by step. Can you check person class weather its having name property? And this.person return the object, then definitely there should be a error in property – CodeMind Aug 22 '21 at 06:23

1 Answers1

1

your error is that the @Inject(MAT_DIALOG_DATA) private person: Person should not be declared as Person object.

Instead, you must do like follows

constructor(private _formBuilder: FormBuilder,
            @Inject(MAT_DIALOG_DATA) private _data: any
            ) { 
               //like this you'll get the person name ;)
                console.log(this._data.person.name);                     
              }
Nizar Khsib
  • 90
  • 1
  • 8
  • Thanks, I edited my question and test the change but the error persist – Andrés Aug 21 '21 at 22:49
  • you're naming dialog data => person So in order to get the person you must do : console.log(this.person.person.name); – Nizar Khsib Aug 21 '21 at 23:00
  • I think It's better to rename private person to private data because the @Inject(MAT_DIALOG_DATA) doesn't really refer to your person object but to the data that you're passing to it. In your case it's just one object, but in other cases you'll need to pass many objects. – Nizar Khsib Aug 21 '21 at 23:02