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

Angular:如何实现父子组件属性双向绑定,保持值同步?

Angular 实现父组件与子组件属性双向同步

要实现父、子组件间属性的双向同步,Angular里最直接的方案是遵循框架的输入属性+输出事件约定来实现双向绑定,以下是针对你提供的示例代码的改造步骤:

1. 修改子组件代码

在子组件中,给childProp添加@Input()装饰器使其成为可接收父组件传入值的输入属性,同时定义一个对应名称的@Output()事件(命名规则为[输入属性名]Change),用于在子组件属性变更时通知父组件更新。

import { Component, Input, Output, EventEmitter } from '@angular/core';

export class ChildComponent {
  values = ['carrot', 'cucumber', 'pepper', 'potato', 'broccoli'];
  index = 0;
  
  // 定义输入属性,接收父组件传入的值
  @Input() childProp = '';
  // 定义对应输出事件,用于向父组件传递变更后的值
  @Output() childPropChange = new EventEmitter<string>();

  changeProp() {
    const newValue = this.values[this.index++ % this.values.length];
    this.childProp = newValue;
    // 触发输出事件,把新值传递给父组件
    this.childPropChange.emit(newValue);
  }
}

子组件的模板无需修改,保持原样即可。

2. 修改父组件模板

在父组件的模板中,使用Angular的双向绑定语法[(属性名)],将父组件的parentProp与子组件的childProp绑定起来:

<p>Parent Property: {{ parentProp }}</p>
<button (click)="changeProp()">Change Parent Property</button>
<!-- 使用双向绑定语法,实现父子属性同步 -->
<app-child [(childProp)]="parentProp"></app-child>

父组件的TS代码无需修改,保持原样即可。

原理说明

Angular的双向绑定本质是“单向输入+单向输出”的语法糖:

  • 当父组件的parentProp变更时,会通过@Input()自动同步到子组件的childProp;
  • 当子组件调用changeProp()修改childProp时,通过childPropChange.emit()触发事件,父组件会自动捕获这个事件并更新parentProp,从而完成双向同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:45:47