You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MdbModalService父组件向模态子组件传递数字ID失败问题问询

问题分析与解决方案

嘿,我一眼就瞅出问题所在了!你在子组件里获取数据的方式完全搞错了——MDB Angular的模态框组件不是通过@Input()来接收传递的数据的,而是要从你注入的modalRef实例里读取!

问题根源

你父组件里用modalService.open()时传入的data对象,会被直接挂载到子组件的modalRef实例上。但你现在在子组件里要么用@Input() data,要么自己定义了passingId,完全没去modalRef里找数据,自然拿到的都是undefined。

另外还要注意大小写:父组件传的是passingID(末尾是大写D),子组件里别写错变量名哦!

修正后的子组件代码

export class SigningPadComponent implements OnInit {
  passingId: number | null = null;

  constructor(public modalRef: MdbModalRef<SigningPadComponent>) {}

  ngOnInit(): void {
    // 从modalRef的data属性里拿到传递的ID
    this.passingId = this.modalRef.data?.passingID;
    console.log("passingId: " + this.passingId);
  }

  // 其他无关函数
}

额外优化(类型安全)

如果想让代码更严谨,可以给传递的数据定义一个接口,让TypeScript帮你做类型校验:

// 定义数据接口
interface ModalData {
  passingID: number;
}

// 子组件里指定modalRef的泛型
export class SigningPadComponent implements OnInit {
  passingId: number | null = null;

  constructor(public modalRef: MdbModalRef<SigningPadComponent, ModalData>) {}

  ngOnInit(): void {
    this.passingId = this.modalRef.data.passingID;
    console.log("passingId: " + this.passingId);
  }
}

你之前传递对象能成功,大概率是用了常规父子组件嵌套的@Input传值方式,但MDB模态框是独立弹出的组件,不属于父组件的DOM子节点,所以@Input根本不会生效~

内容的提问来源于stack exchange,提问作者Yannick Mussche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:34:08