首页 文章

多个组件绑定相同的反应形式控制更新问题

提问于
浏览
4

在某些情况下,我们可能需要将多个表单组件绑定到同一个表单控件 . 我对处理这种情况的角度方式感到困惑:

更改其中一个组件值时,将更改表单值,但不会更改其他组件值 .

我在这种情况下做的解决方法是使用表单值修补from,这很难看:

this.form.patchValue(this.form.value);

Here is a stackblitz demo for my issue,我为输入更改添加了变通方法而不是选择以便更好地理解 .

是否有一种优雅的方式来处理角度反应形式的情况?

1 回答

  • 6

    一个不需要添加任何 (change) 侦听器的好反应解决方案是创建两个单独的名称控件,并通过订阅 valueChanges stream使它们保持同步 .

    component.ts

    import { Component, NgModule, ViewChild } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      templateUrl: 'app.component.html'
    })
    export class AppComponent {
      form: FormGroup;
    
      constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
          nameText: '',
          nameSelect: '',
        })
    
        const text = this.form.get('nameText');
        const select = this.form.get('nameSelect');
    
        text.valueChanges.subscribe(v => select.setValue(v, { emitEvent: false }));
        select.valueChanges.subscribe(v => text.setValue(v, { emitEvent: false }));
      }
    
    }
    

    component.html

    <form [formGroup]="form">
      When you change the input, the select changes : <br>
      <input type="text" formControlName="nameText"><br>
      When you change the select, the input does not change : <br>
      <select formControlName="nameSelect">
        <option value="value1">value1</option>
        <option value="value2">value2</option>
      </select>
    </form>
    

    Live demo

相关问题