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

Angular中2 ways data binding(双向数据绑定)的使用方法是什么?

Angular 双向绑定与组件间数据共享实现指南

双向数据绑定的具体使用

Angular 中双向绑定的核心语法是[(ngModel)],本质是属性绑定[]和事件绑定()的语法糖,使用前需要先在对应模块导入FormsModule:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; 
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

基础使用示例:

// 组件类定义绑定属性
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  userName = '';
}
<!-- 模板中使用双向绑定 -->
<input type="text" [(ngModel)]="userName" placeholder="输入用户名">
<p>当前输入值:{{ userName }}</p>

以上代码等价于手动实现属性+事件绑定:

<input [value]="userName" (input)="userName = $event.target.value">

如果需要给自定义组件实现双向绑定,需要遵循@Input()+同名Change后缀@Output()的命名规则:

// 自定义输入组件
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
  selector: 'app-custom-input',
  template: `<input [value]="value" (input)="onChange($event)">`
})
export class CustomInputComponent {
  @Input() value: string = '';
  // 输出事件名必须为「输入属性名+Change」
  @Output() valueChange = new EventEmitter<string>();

  onChange(event: Event) {
    this.valueChange.emit((event.target as HTMLInputElement).value);
  }
}

父组件调用时即可直接使用双向绑定语法:

<app-custom-input [(value)]="userName"></app-custom-input>

组件间数据共享的常用实现方式

父组件向子组件传值:@Input()

子组件定义接收属性:

import { Component, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  template: `<p>父组件传入值:{{ parentMsg }}</p>`
})
export class ChildComponent {
  @Input() parentMsg: string = '';
}

父组件传值:

<app-child [parentMsg]="sendToChildMsg"></app-child>

子组件向父组件传值:@Output() + EventEmitter

子组件定义输出事件:

import { Component, Output, EventEmitter } from '@angular/core';
@Component({
  selector: 'app-child',
  template: `<button (click)="sendMsg()">给父组件传值</button>`
})
export class ChildComponent {
  @Output() childMsgEvent = new EventEmitter<string>();
  private childMsg = '我是子组件的数据';

  sendMsg() {
    this.childMsgEvent.emit(this.childMsg);
  }
}

父组件监听事件接收值:

<app-child (childMsgEvent)="getMsg($event)"></app-child>
<p>子组件传入值:{{ receivedMsg }}</p>
// 父组件类定义接收方法
receivedMsg = '';
getMsg(data: string) {
  this.receivedMsg = data;
}

无关联/跨多层组件传值:服务+RxJS

创建全局单例共享服务,用RxJS的Subject类保存可观察状态:

// shared-data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' }) // 根注入,全局单例
export class SharedDataService {
  // BehaviorSubject 会给新订阅者返回最新值
  private dataSubject = new BehaviorSubject<string>('初始值');
  public data$ = this.dataSubject.asObservable();

  updateData(newVal: string) {
    this.dataSubject.next(newVal);
  }
}

任意组件都可以注入服务,更新/订阅共享数据:

// 写入数据的组件
import { SharedDataService } from './shared-data.service';
export class ComponentA {
  constructor(private sharedService: SharedDataService) {}
  update() {
    this.sharedService.updateData('新的共享值');
  }
}
// 读取数据的组件
import { SharedDataService } from './shared-data.service';
export class ComponentB implements OnInit {
  sharedVal = '';
  constructor(private sharedService: SharedDataService) {}

  ngOnInit() {
    this.sharedService.data$.subscribe(val => {
      this.sharedVal = val;
    });
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:15:02