Angular Form

Form

FormControl 追踪单个表单控件的值和验证状态
FormGroup
FormArray
ControlValueAccessor

响应式表单

模板驱动表单

setValue vs patchValue[1(#refer-anchor-1)]

setValue must set the value of all the controls

1
formgroup.setValue({name:'xiaoming', age:'20'});

patchValue can only assign one of controls

1
formgroup.setValue({name:'xiaoming'});

Dynamic change validator need to update handly

1
2
3
4
5
6
7
8
9
10
// reset
Object.keys(this.basicForm.controls).forEach(key => {
this.basicForm.get(key)!.setValidators(null);
this.basicForm.get(key)!.enable();
});
this.basicForm.get('a')!.patchValue(1);
this.basicForm.get('b')!.setValidators(Validators.required);
Object.keys(this.basicForm.controls).forEach(key => {
this.basicForm.get(key)!.updateValueAndValidity({ onlySelf: false });
});

Active trigger verification

查看是否验证失败

1
2
3
4
5
6
Object.keys(this.editForm.controls).forEach(controlName => {
const control = this.editForm.controls[controlName];
if (!control.valid) {
console.log(`Control '${controlName}' is invalid.`);
}
});

Reference

- [1] [Setvalue vs Patchvalue Angular](https://sami-chkhachkhi.medium.com/setvalue-vs-patchvalue-angular-a64a55e912b8)

本文作者: 孟 虎
本文链接: https://menghu1994.github.io/blog/2023/10/Angular/Form/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!