首页 > 解决方案 > 无法在 2 个或更多组件实例之间共享一个表单控件实例

问题描述

我有 2 个电话号码字段应该同步,即更改第一个电话号码字段应该更新第二个电话号码字段,反之亦然。

  1. 我曾尝试共享一个 fromControl 实例 b/w 那些不起作用的 2 个电话号码字段组件。 https://stackblitz.com/edit/angular-ha16re?file=app/form-field-custom-control-example.html

  2. 我也尝试过使用 ngModel 也没有用。

<mat-form-field>
  <example-tel-input 
    placeholder="Phone number" 
    [formControl]="selectedTel"></example-tel-input>
</mat-form-field>

<mat-form-field>
  <example-tel-input 
    placeholder="Phone number copy" 
    [formControl]="selectedTel"></example-tel-input>
</mat-form-field>
  selectedTel = new FormControl();

  constructor() {
    this.selectedTel.valueChanges.subscribe(newVal => {
      console.log('selected tel number is:', newVal);
    });

我期望这两个字段应该是同步的。

标签: angularangular-reactive-formsform-control

解决方案


尝试将您的订阅更改为:

this.selectedTel.valueChanges.subscribe(newVal => {

       this.selectedTel.setValue(newVal, {emitEvent:false});
       console.log('selected tel number is:', newVal);
    });

推荐阅读