Angular不使用FormControl/FormGroup时如何重置自定义表单对象
解决方案
TypeScript 原生普通类没有内置的 reset 方法,你可以通过以下几种方案实现需求,不需要手动逐个给属性赋值:
方案1:直接重新实例化(改动最小,推荐)
你初始化表单时就是创建的 DealDispositionFormFields 空实例,重置时直接重新new一个实例赋值给原变量即可,ngModel会自动同步更新所有表单字段的值。
先调整类定义,给所有属性设置默认值为null:
class DealDispositionFormFields { dealName: string | null = null; summary: string | null = null; dealDispositionType: string | null = null; terminationPayment: number | null = null; effectiveDate: string | null = null; totalBrokerCommission: number | null = null; effectiveDateString: string | null = null; dealId: number | null = null; }
重置时只需要一行代码:
this.dealDispositionFormFields = new DealDispositionFormFields();
方案2:给类内置reset方法(符合你预期的.reset()调用习惯)
如果你想要和你期望一致的 this.dealDispositionFormFields.reset() 调用方式,直接给类新增reset方法即可,不需要替换实例引用,适合有其他逻辑依赖原实例引用的场景:
class DealDispositionFormFields { dealName: string | null = null; summary: string | null = null; dealDispositionType: string | null = null; terminationPayment: number | null = null; effectiveDate: string | null = null; totalBrokerCommission: number | null = null; effectiveDateString: string | null = null; dealId: number | null = null; // 新增reset方法 reset() { Object.keys(this).forEach(key => { // 跳过方法类型的属性,避免把类方法置为null if (typeof (this as any)[key] !== 'function') { (this as any)[key] = null; } }) } }
调用方式完全符合你的预期:
this.dealDispositionFormFields.reset();
方案3:通用重置函数(不想改动原类定义时使用)
如果你不希望修改原DealDispositionFormFields类的定义,可以在组件内写一个通用重置方法,遍历实例属性统一置为null:
// 组件内新增通用重置方法 resetObjectProperties(instance: any) { Object.keys(instance).forEach(key => { if (typeof instance[key] !== 'function') { instance[key] = null; } }) } // 调用时传入表单实例即可 this.resetObjectProperties(this.dealDispositionFormFields);
以上三种方案后续新增表单属性时都不需要修改重置逻辑,自动适配新属性。
内容的提问来源于stack exchange,提问作者Jaya Reddy
相关产品推荐
相关产品推荐

