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

Angular子组件向父组件推送数据重复的问题求助

关于Angular子组件向父组件推送数据重复的问题排查

问题描述

学习Angular时遇到问题:表格基于传感器对象数组渲染,通过子组件向父组件推送新传感器对象时,同一数据被添加两次,表格中出现两条属性完全相同的新传感器记录。

相关代码实现

父组件SensorsTableComponent

@Component({
  selector: "app-sensors-table",
  templateUrl: "./sensors-table.component.html",
  styleUrls: "./sensors-table.component.css"
})
export class SensorsTableComponent{
  sensors: ISensor[] = sensors;

  addSensor(sensor: ISensor){
    this.sensors.push(sensor)
  }
  // ...其他代码
}

父组件模板调用子组件

<app-add-sensor-modal
  [active]="addSensorModalActive"
  (onModal)="changeAddSensorModal($event)"
  (onSensors)="addSensor($event)"
></app-add-sensor-modal>

子组件AddSensorModalComponent

@Component({
  selector: "app-add-sensor-modal",
  templateUrl: "./add-sensor-modal.component.html",
  styleUrls: "./add-sensor-modal.component.css"
})
export class AddSensorModalComponent implements OnInit{
  @Output() onSensors = new EventEmitter<ISensor>()

  addSensor(){
    let sensor: ISensor = {
      id: Math.random(),
      name: this.form.value.name,
      model: this.form.value.model,
      range_from: this.form.value.range_from,
      range_to: this.form.value.range_to,
      type: this.form.value.type,
      unit: this.form.value.unit,
      location: this.form.value.location,
      description: this.form.value.description
    }
    this.onSensors.emit(sensor)
    this.closeModal()
  }
  // ...其他代码
}

可能的问题原因及排查方向

  • 子组件addSensor方法被重复触发:检查子组件模板,是否存在多个触发该方法的事件绑定(比如提交按钮同时绑定了click和表单ngSubmit,或者按钮嵌套在表单内未阻止事件冒泡,导致click和submit都触发方法)。
  • 父组件重复绑定事件或渲染子组件:确认父组件模板中是否多次渲染了<app-add-sensor-modal>组件,或者同一个组件实例上重复绑定了(onSensors)事件。
  • 变更检测导致重复执行:在addSensor方法中添加console.log日志,确认方法是否被调用多次;若因变更检测触发重复执行,可尝试使用ChangeDetectorRef手动控制变更检测周期。
  • 事件冒泡未阻止:如果子组件的提交按钮在表单标签内,按钮的click事件会触发表单的submit事件,若两者都绑定了调用addSensor的逻辑,就会导致两次推送,可给按钮添加(click)="addSensor(); $event.stopPropagation()"或改用表单ngSubmit统一处理提交逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:10:13