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

如何将子组件布尔值传递给父组件以控制同级子组件?

问题解决方法

1. 解决addressExists打印undefined的问题

你当前的代码只声明了addressExists变量,但既没有初始化,也没在异步请求的回调中给它赋值。而且getPersonInfo是异步请求,ngOnInit执行时,请求还没完成,此时打印addressExists自然是undefined。修正步骤:

  • 给addressExists设置初始值,比如默认设为false:
    addressExists: boolean = false;
    
  • 在getPersonInfo的subscribe回调中,给addressExists赋值:
    this.personService.getPersonInfo(this.personId).subscribe((res => {
       ...
       this.addressExists = res.body.personInfo; // 新增赋值逻辑
       this.updateAddress(res.body.personInfo);
       ...
    }))
    

2. 确保父组件正确控制company-list的显示

为避免父组件personInfo初始状态的不确定性,建议给它也设置初始值:

// person.component.ts
personInfo: boolean = false;

额外检查点

  • 确认getPersonInfo接口返回的res.body.personInfo确实是布尔类型,避免传递null、undefined或其他类型值导致*ngIf判断异常
  • 给异步请求添加错误处理,避免因请求失败导致addressPresent事件从未触发,父组件personInfo一直处于初始状态:
    this.personService.getPersonInfo(this.personId).subscribe({
      next: (res) => {
        ...
        this.addressExists = res.body.personInfo;
        this.updateAddress(res.body.personInfo);
        ...
      },
      error: (err) => {
        // 错误时默认设置为false
        this.addressExists = false;
        this.updateAddress(false);
        console.error('获取人员信息失败:', err);
      }
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 23:43:13