Search code examples
angularinputcomponentsangular7angular8

Get object after open modal with @Input directive from component


I want get object when open Modal component and get the value passed from component.

So this is my method inside UserComponent.ts to open ModifyuserModalComponent:

  constructor(
    public dialog: MatDialog
  ) { }

  modifyUser(user: UteUser) {
    console.log(user); //this print correctlry my object
    this.dialog.open(ModifyuserModalComponent, {
      data: user
    });
  }

and this my ModifyuserModalComponent ts code:

@Component({
  selector: 'app-modifyuser-modal',
  templateUrl: './modifyuser-modal.component.html',
  styleUrls: ['./modifyuser-modal.component.scss'],
})
export class ModifyuserModalComponent implements OnInit {

  @Input() data: any;

  constructor(
    public dialogRef: MatDialogRef<ModifyuserModalComponent>
  ) { 

  }

  ngOnInit() {
    console.log("usergetted: ", this.data);
  }

  closeDialog(){
    this.dialogRef.close();
  }
}

So my target is get data from UserComponent.ts when I click to open dialog. But when open ModifyuserComponent my data object is undefined. Where am I wrong?


Solution

  • this.dialog.open(ModifyuserModalComponent, {
      data: user
    }); 
    

    returns a MatDialogRef, on which in turn you can access the instantiated component.

    Therefore this will work:

    const modalRef = this.dialog.open(ModifyuserModalComponent, {
      data: user
    });
    const modal = modalRef.componentInstance
    modal.data... // your code goes here