Associating multiple components with the same form control update problem

In some situations, we may need to bind multiple form components to a single form control. And I'm confused by the angular way of handling this case:

When you change the value of one of the components, the value of the form changes, but not the values ​​of the other components.

The workaround I made in this case is to fix from from a form value that looks awful:

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

Here is a demo of stacks for my problem , I added a workaround to change the input, not a choice for a better understanding.

Is there an elegant way to handle this with angular reactive molds?

+6
source share
1 answer

A good reactive solution that does not require the addition of (change)listeners would be to create two separate name controls and synchronize them by subscribing to the stream valueChanges.

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

+6
source

Source: https://habr.com/ru/post/1696303/


All Articles