如何获取以Angular反应形式更改了值的字段的FormControlName

时间:2019-06-24 02:35:18

标签: javascript angular typescript rxjs

我有一个反应式表单,其中包含10多个表单控件,并在valueChanges上使用订阅,可观察到以检测更改。它工作完美,但输出始终是整个表单值对象(意味着所有表单控件及其值)。有没有一种方法可以简单地获取已更改字段的表单控件名称?

this.form = this.fb.group({
    field1: ['', Validators.required],
    field2: ['', Validators.required],
    field3: ['', Validators.required],
    field4: ['', Validators.required],
    field5: ['', Validators.required],
    field6: ['', Validators.required],
    field7: ['', Validators.required],
    field8: ['', Validators.required],
    field9: ['', Validators.required],
    field10: ['', Validators.required],
    field11: ['', Validators.required],
    field12: ['', Validators.required],
    field13: [{ value: '', disabled: true }, Validators.required]
});

this.form.valueChanges.subscribe(
    result => this.calculateParams(result)
);

calculateParams(result) {
    console.log(result); // giving the entire form.value object
}

6 个答案:

答案 0 :(得分:1)

您可以使用get方法和对其上的valueChanges方法进行访问,将formcontrol与formgroup隔离。

this.form.get('formcontrolName').valueChanges()

注意:form.get返回AbstractControl,上面也带有valueChanges方法。

答案 1 :(得分:1)

还没有完全测试代码,但是想法是将控件及其键配对,然后同时在每个控件上侦听valueChanges并返回对象键而不是值(当然,您可以将value和输出的键)

const fields={
    field1: ['', Validators.required],
    field2: ['', Validators.required],
    field3: ['', Validators.required],
    field4: ['', Validators.required],
    field5: ['', Validators.required],
    field6: ['', Validators.required],
}

zip(
 from(Object.values(fb.group(fields).controls)),
 from(Object.keys(fields))
).pipe(mergeMap([control,key])=>control.valueChanges.pipe(mapTo(key)))

答案 2 :(得分:1)

这是一种变通方法,但是如果存储旧值,您可以执行类似的操作

this.old={...this.myForm.value}
this.myForm.valueChanges.subscribe(res=>{
  const key=Object.keys(res).find(k=>res[k]!=this.old[k])
  this.old={...this.myForm.value}
})

答案 3 :(得分:0)

您可以单独订阅每个更改。

From

对我来说,这有点棱角分明。

答案 4 :(得分:0)

Eliseo的answer的rxjs方式

this.form.valueChanges.pipe(
    startWith(this.form.value),
    pairwise(),
    map(([oldValues, newValues]) => {
        return Object.keys(newValues).find(k => newValues[k] != oldValues[k]);
    }),
).subscribe(key => {
    console.log( key )
});

答案 5 :(得分:0)

将控件动态添加到 valueChanges 后,对每个控件使用 FormGroup

const ct = {key: 'myControl'};    
this.myForm.addControl(ct.key, new FormControl('', Validators.required))
this.myForm.controls[ct.key].valueChanges
.subscribe(d => {
    // here ct will be available as closure , so that we can access every form control here and do operation accordingly
    console.log(d, ct.key);
})

此处 ct 对象将在 subscribe 内作为闭包可用。