Angular6嵌套表单的验证

匿名 (未验证) 提交于 2019-12-02 23:00:14

嵌套表单

ngOnInit()中的表单验证

以下文代码为例,表单validateForm中包含三个子表单,每个表单中有一定的字段值,初始化表单验证:
ngOnInit() {
this.validateForm = this.fb.group({
bizMeruser: this.fb.group({ // 登录信息
username: [’’, [Validators.required]], // 管理登录账号
}),
bizMerchantBasic: this.fb.group({ // 商户/公司基础信息
merchantFullName: [’’, [Validators.required, Validators.maxLength(32)]], // 全称
merchantShortName: [’’, [Validators.required, Validators.maxLength(32)]], // 简称
merchantRepresent: [’’, [Validators.required, Validators.maxLength(32)]], // 法人代表
merchantAddress: [’’, [Validators.required, Validators.maxLength(32)]], // 供应商地址
merchantFirstowner: [’’, [Validators.required, Validators.maxLength(32)]], // 联系人1

}),
bizMerchantFreight: this.fb.group({ // 供应商运费
merchantFreight: [’’, [Validators.required, Validators.maxLength(32)]], // 运费信息

})
});
/* 加载页面字段值 */
if (!this.isAdd) { // 查看或修改页面
this.commercialProvider.getDataById(this.id).subscribe(res => {
this.initFormData(res);
});
} else {
this.isSpinning = false;
}
}

初始化表单的方法

/**

  • 初始化form
  • @param data
    */
    initFormData(data) {
    this.validateForm.controls[‘bizMeruser’].setValue({
    username: _.get(data.bizMeruser, ‘username’, ‘’)
    });
    this.validateForm.controls[‘bizMerchantBasic’].setValue({
    merchantFullName: _.get(data.bizMerchantBasic, ‘merchantFullName’, ‘’),
    merchantShortName: _.get(data.bizMerchantBasic, ‘merchantShortName’, ‘’),
    merchantRepresent: _.get(data.bizMerchantBasic, ‘merchantRepresent’, ‘’),
    merchantAddress: _.get(data.bizMerchantBasic, ‘merchantAddress’, ‘’),
    merchantFirstowner: _.get(data.bizMerchantBasic, ‘merchantFirstowner’, ‘’),
    merchantFirstphone: _.get(data.bizMerchantBasic, ‘merchantFirstphone’, ‘’),
    merchantSencondowner: _.get(data.bizMerchantBasic, ‘merchantSencondowner’, ‘’),
    merchantSencondphone: _.get(data.bizMerchantBasic, ‘merchantSencondphone’, ‘’),
    merchantEmail: _.get(data.bizMerchantBasic, ‘merchantEmail’, ‘’),

    });
    this.validateForm.controls[‘bizMerchantFreight’].setValue({
    merchantFreight: _.get(data.bizMerchantFreight, ‘merchantFreight’, ‘’),
    merchantAmount: _.get(data.bizMerchantFreight, ‘merchantAmount’, ‘’),
    });
    this.isSpinning = false;
    }

表单验证的方法

getFormGroupControl(group, name) {
return this.validateForm.get(group).get(name);
}

保存方法中怎么取到每个字段

doSave(event, value) {
event.preventDefault();
const controls = this.validateForm.controls;
for (const key in controls) {
if (controls.hasOwnProperty(key)) {
const group = this.validateForm.get(key) as FormGroup;
const items = group.controls;
for (const key2 in items) {
if (items.hasOwnProperty(key2)) {
group.controls[key2].markAsDirty();
group.controls[key2].updateValueAndValidity();
}
}
}
}
if (!this.validateForm.invalid) {
console.dir(‘取到字段了!’);

} else {
console.dir(‘kkkkkkk’);
}

页面中表单的写法

效果


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!