以我的项目作为示例,总结一下Angular响应式表单的应用和常用的方法:
1.创建表单
form.ts代码
import { Component, OnInit } from "@angular/core";
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
@Component({
selector: "app-form",
templateUrl: "./form.component.html"
})
export class SLSDetailComponent implements OnInit{
slsForm: FormGroup;//定义表单slsForm
ngOnInit(): void {
this.createForm();//初始化创建表单
}
createForm() {//创建项目需要的数据(多层嵌套的数据)
this.slsForm = this.fb.group({
UserServiceDescription: this.fb.group({}),
VPL: this.fb.group({})
});
}
//setControl设置值
this.slsForm.setControl(
"UserServiceDescription",
this.fb.group({
sgServiceIdRef: [sls.desc.sgServiceIdRef],
serviceId: [
sls.desc.serviceId,
[Validators.required, Validators.min(0)]
],
serviceStatus: [sls.desc.serviceStatus, Validators.required],
Name: this.fb.array(sls.desc.names.map(name => this.fb.group(name))),
ServiceLanguage: this.fb.array(
sls.desc.serviceLanguages.map(lang => this.fb.control(lang))
)
})
);
this.slsForm.setControl(
"VPL",
this.fb.group({
CT: this.fb.array(sls.vpl.cts.map(ct => this.createCtForm(ct))),
UC: this.fb.array(sls.vpl.unicasts.map(uc => this.createUcForm(uc))),
VOD: this.fb.array(
sls.vpl.unicastVods.map(vod => this.createVodForm(vod))
),
BFP: this.fb.array(sls.vpl.bfps.map(bfp => this.createBfpForm(bfp)))
})
);
}
访问FormGroup、FormArray方法:
get userServiceDescription(): FormGroup {
return this.slsForm.get("UserServiceDescription") as FormGroup;
}
get vpl(): FormGroup {
return this.slsForm.get("VPL") as FormGroup;
}
get names(): FormArray {
return this.userServiceDescription.get("Name") as FormArray;
}
get serviceLanguages(): FormArray {
return this.userServiceDescription.get("ServiceLanguage") as FormArray;
}
get cts(): FormArray {
return this.vpl.get("CT") as FormArray;
}
//访问某个FormArray下的FormArray(双层嵌套)
getCtCtUrls(index: number): FormArray {
return this.cts.at(index).get("CtUrl") as FormArray;
}
为FormArray添加一条数据:
addName(name?: Name) {
let newName = name ? name : SchemaService.defaultServiceName;
this.names.push(
this.fb.group({
text: [newName.text, Validators.required],
lang: [newName.lang]
})
);
}
删除某条FormArray中的数据:
deleteFromFormArray(formArray: FormArray, index: number) {
formArray.removeAt(index);
}
全部删除FormArray的数据:
deleteAll(formArray: FormArray) {
formArray.controls.splice(0);
formArray.setValue([]);
}
patchValue设置某个FormControl的值,更新表单的值:
onServiceIdSelected(serviceId: string) {
this.slsForm.patchValue({
UserServiceDescription: {
sgServiceIdRef: serviceId
}
});
}
patchValue和setValue: