使用 Angular 的反应形式 + 嵌套 FormGroups: https://angular.io/guide/reactive-forms#nested-formgroups
通常,当页面加载时,您的表单应该有 3 个组(每个“表单”1 个)。
声明形式为:
this.form = this.fb.group({
subForm1: this.fb.group({
subForm1_field1: ['', Validators.required ],
subForm1_field2: ['', Validators.required, Validators.min(5) ],
}),
subForm2: this.fb.group({
subForm2_field1: '',
subForm2_field2: ['', Validators.required, Validators.max(10) ],
}),
subForm3: this.fb.group({
subForm3_field1: '',
})
});
所以最后对于提交按钮,您只能使用父表单来获取验证状态(如果任何嵌套表单组中的任何字段无效,它将是false)。 HTML 代码:
<input type="checkbox" (ngModel)="onShowSubForm3()"/><label>Show Form3</label>
<form [formGroup]="form">
<div class="form-horizontal"><!-- your inputs goes here for subForm1 --></div>
<div class="form-horizontal"><!-- your inputs goes here for subForm2 --></div>
<div class="form-horizontal" *ngIf="showSubForm3"><!-- your inputs goes here for subForm3 --></div>
</form>
<button type="button" (click)="submitSubForm1()" [disabled]="!form.get("subForm3").valid">Send 1</button> <!-- is disabled only if any field from `subForm3` is invalid -->
<button type="button" (click)="submitAllForms()" [disabled]="!form.valid">Send All</button> <!-- is disabled if any field is invalid -->
发送表单/发送 1 个子表单的代码:
submitAllForms(){
let formValue = this.form.value();
/*formValue = {
subForm1: {
subForm1_field1: "val1-1",
subForm1_field2: "val1-2",
},
subForm2: {
subForm2_field1: "val2-1",
subForm2_field2: "val2-2",
},
};*/
this.http.post("/url", {data: formValue});
}
submitSubForm1(){
let subForm1Value = this.form.get["subForm1"].value;
/*subForm1Value = {
subForm1_field1: "val1-1",
subForm1_field2: "val1-2",
};*/
this.http.post("/url", {data: subForm1Value});
}
每次您需要显示/隐藏新的子表单时 - 更新 this.form(您可能想要存储所有字段,但仅更新 Validators)。
showSubForm3: boolean = false;
onShowSubForm3(value){
this.showSubForm3 = value;
//THIS CODE CAN BE OPTIMIZED TO UPDATE ENTIRE `FormGroup` WITH NEW VALIDATORS
let field = this.form.controls["subForm3.subForm3_field1"];
if(value){
field.setValidators(Validators.compose([Validators.required]));
}else{
field.setValidators(Validators.compose([]));
}
field.updateValueAndValidity();
}