gpt4 book ai didi

angular - react 形式: mark dirty all controls in form group

转载 作者:行者123 更新时间:2023-12-03 15:21:40 29 4
gpt4 key购买 nike

我有带表格的Angular 6应用程序。这是一个例子

export class ExampleComponent implements OnInit {
form: FormGroup;

constructor(private fb: FormBuilder) { }

ngOnInit() {
this.form = new FormGroup({
first: new FormControl(),
last: new FormControl()
});

this.markControlsAsDirty(this.form);
}

markControlsAsDirty(form: FormGroup) {
this.form.get('first').markAsDirty();
this.form.get('last').markAsDirty();
}
}

我不想得到一个控件并标记每个字段。
我可以将表单组中的所有控件标记为脏吗?

更新我已经添加了 stackblitz example,以表明先前的两个答案是错误的

最佳答案

如果您具有复杂的表单结构,则可以隔离代码以将FormGroupFormArrayFormControl标记为脏。在这里查看示例:Mark Form as dirty

markDirty() {
this.markGroupDirty(this.form);
console.log('FORM:', this.form);}
markGroupDirty(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(key => {
switch (formGroup.get(key).constructor.name) {
case "FormGroup":
this.markGroupDirty(formGroup.get(key) as FormGroup);
break;
case "FormArray":
this.markArrayDirty(formGroup.get(key) as FormArray);
break;
case "FormControl":
this.markControlDirty(formGroup.get(key) as FormControl);
break;
}
});
}
markArrayDirty(formArray: FormArray) {
formArray.controls.forEach(control => {
switch (control.constructor.name) {
case "FormGroup":
this.markGroupDirty(control as FormGroup);
break;
case "FormArray":
this.markArrayDirty(control as FormArray);
break;
case "FormControl":
this.markControlDirty(control as FormControl);
break;
}
});
}
markControlDirty(formControl: FormControl) {
formControl.markAsDirty();
}

关于angular - react 形式: mark dirty all controls in form group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54943261/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com