如果您从另一个编辑一个FormControl,则FormGroup valueChanges返回相同的值

时间:2019-10-10 23:35:44

标签: angular angular-reactive-forms reactive-forms

(在Angular 8.2.9上测试)

嗨, 我试图用反应形式来编辑基于另一个字段的字段,并且还订阅整个pipeline { agent { docker { image 'python:3.7.0' } } environment { ENV = 'test' } stages { stage('install dependencies') { steps { sh 'pip install -r requirements.txt' } } stage('test') { steps { sh 'python app/tests/test_user.py' } } } 。我的观察结果是,如果我将基于FormGroup.valueChanges的更改更改为另一个FormControl.valueChanges,那么我将从FormControl.setValue得到两个相同的更改。相反,如果我仅对两个FormGroup执行两次setValue,则结果为可接受。

示例代码:

FormControl

结果是:

import {Component} from '@angular/core';
import {FormBuilder} from '@angular/forms';

@Component({
  selector: 'app-myform',
  template: '',
})
export class MyformComponent {

  form = this.builder.group({
      a: '',
      b: '',
    });

  constructor(private builder: FormBuilder) {
    this.form.get('a').valueChanges.pipe(
    ).subscribe((change) => {
      this.form.get('b').setValue('second');
      console.log(`a = ${change}`);
    });

    this.form.get('b').valueChanges.subscribe((change) => {
      console.log(`b = ${change}`);
    });

    this.form.valueChanges.subscribe((change) => {
      console.log(`obj = ${JSON.stringify(change)}`);
    });

    this.form.get('a').setValue('first');
    this.form.get('b').setValue('third');
  }

}

我期望的是

b = second 
obj = {"a":"first","b":"second"} 
a = first 
obj = {"a":"first","b":"second"} 
b = third 
obj = {"a":"first","b":"third"} 

如果我删除了b = second obj = {"a":"first","b":""} a = first obj = {"a":"first","b":"second"} b = third obj = {"a":"first","b":"third"} 行,则其行为与我期望的一样:

this.form.get('b').setValue('second');

我想知道是什么原因导致了这种行为,以及它是否按预期工作或应该作为错误受到威胁。

0 个答案:

没有答案