如何获取值在 Angular 反应形式中更改的字段的 FormControlName [英] How to get FormControlName of the field which value changed in Angular reactive forms

查看:34
本文介绍了如何获取值在 Angular 反应形式中更改的字段的 FormControlName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个响应式表单,其中包含 10 多个表单控件,并使用对 valueChanges observable 的订阅来检测更改.它工作得很好,但输出始终是整个表单值对象(意味着所有表单控件及其值).有没有办法简单地获取更改的字段的表单控件名称?

I have a reactive form with over 10 form controls and using subscription on valueChanges observable to detect changes. It works perfectly but output is always the entire form value object(meaning all the form controls and their values). Is there a way to simply get the form control name of the field that changed?

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
}

推荐答案

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

It's a work-around but if store the old values you can do some like

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}
})

这篇关于如何获取值在 Angular 反应形式中更改的字段的 FormControlName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆