angular – 多个组件绑定相同的响应式控件更新问题

前端之家收集整理的这篇文章主要介绍了angular – 多个组件绑定相同的响应式控件更新问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在某些情况下,我们可能需要将多个表单组件绑定到同一个表单控件.我对处理这种情况的角度方式感到困惑:

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

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

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

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

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

解决方法

一个不需要添加任何(更改)侦听器的好的反应式解决方案是创建两个单独的名称控件,并通过订阅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

猜你在找的Angularjs相关文章