使用@Input指令从组件打开模态后获取对象

问题描述 投票:0回答:1

我希望在打开Modal组件时获取对象并获取从组件传递的值。

所以这是我在UserComponent.ts中打开ModifyuserModalComponent的方法:

  constructor(
    public dialog: MatDialog
  ) { }

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

和我的ModifyUserModalComponent ts代码:

@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();
  }
}

所以我的目标是单击打开对话框时从data获得UserComponent.ts。但是当打开ModifyuserComponent时,我的数据对象是undefined。我在哪里错了?

angular input components angular7 angular8
1个回答
0
投票
this.dialog.open(ModifyuserModalComponent, {
  data: user
}); 

返回MatDialogRef,您可以依次在其上访问实例化的组件。

因此这将起作用:

const modalRef = this.dialog.open(ModifyuserModalComponent, {
  data: user
});
const modal = modalRef.componentInstance
modal.data... // your code goes here
© www.soinside.com 2019 - 2024. All rights reserved.