Angular中如何对比两个表单对象?同控件名不同表单组场景
对比oldAuditLog与newAuditLog表单组的控件值
实现步骤(以Angular表单为例)
获取表单组实例:从父表单中分别提取两个目标表单组
const oldAuditLogGroup = this.parentForm.get('oldAuditLog') as FormGroup; const newAuditLogGroup = this.parentForm.get('newAuditLog') as FormGroup;提取控件名称列表:由于两个表单组的
formControlName一致,只需从其中一个组中获取所有控件名const controlNames = Object.keys(oldAuditLogGroup.controls);遍历对比控件值:逐个对比对应控件的值,收集差异项
// 存储差异结果的数组 const differences: { controlName: string; oldValue: any; newValue: any }[] = []; controlNames.forEach(name => { const oldValue = oldAuditLogGroup.get(name)?.value; const newValue = newAuditLogGroup.get(name)?.value; // 基本类型直接对比,复杂类型需用深比较 if (oldValue !== newValue) { differences.push({ controlName: name, oldValue: oldValue, newValue: newValue }); } });处理复杂类型的深对比:如果控件值是对象、数组这类引用类型,需要用深比较函数判断是否相等。可以自己实现深比较,或者使用成熟工具库(如lodash的
isEqual):import { isEqual } from 'lodash'; // 替换上述对比逻辑 if (!isEqual(oldValue, newValue)) { differences.push({ controlName: name, oldValue: oldValue, newValue: newValue }); }使用差异结果:完成对比后,
differences数组会包含所有值不一致的控件信息,可用于打印日志、展示差异等场景:console.log('表单值差异:', differences);
内容的提问来源于stack exchange,提问作者lollipoplorlipop
相关产品推荐
相关产品推荐

