Afi*_*Afi 5 formbuilder angular2-forms angular
我有一个添加不同的字段(我添加新的控件,因为只是使用*ngIf将它们从模板中隐藏起来,因此不会从表单中将它们排除,因此导致表单无效)基于select选项中的选定选项.我正在使用Angular2中的表单的addControl方法向可用表单添加新控件.控件正在正确添加,但我不知道为什么这些添加的控件的值在用户输入后没有更新.以下是我向表单添加新控件的方法:
signUpForm: ControlGroup;
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.signUpForm = this.fb.group({
firstName: ["", Validators.required],
lastName: ["", Validators.required],
group: ["", Validators.required]
});
}
modifyControls(selectedGroup): number {
if (selectedGroup == 1) {
if (this.signUpForm.contains("studentID")) {
this.signUpForm.removeControl("studentID");
}
this.signUpForm.addControl("teacherCode", new Control("", Validators.required));//need some custome validations
this.signUpForm.addControl("teacherID", new Control("", Validators.required));
return 1;
}
else if (selectedGroup == 2) {
if (this.signUpForm.contains("teacherCode")) {
this.signUpForm.removeControl("teacherCode");
this.signUpForm.removeControl("teacherID");
}
this.signUpForm.addControl("studentID", new Control("", Validators.required));
return 2;
}
}
Run Code Online (Sandbox Code Playgroud)
看起来角度不能识别那些新的领域.我认为它与AbstractControl有关,但文档缺乏这一点.以下是问题的快照,即动态添加的控件未被角度拾取.

为了显示问题,我在下面的plunker中创建了一个简单的例子(请转到版本2来复制此问题).
https://plnkr.co/edit/RI4JL4Pnf2LrJ3TsxsSt?p=preview
我做错了什么以及如何使其适用于当前的设置?实现相同行为的其他选择有哪些?
谢谢您的帮助
解决方法:
modifyControls(selectedGroup) {
if (selectedGroup == 1) {
this.signUpForm.controls['teacherCode'].validator = Validators.required;
this.signUpForm.controls['teacherCode'].updateValueAndValidity();
this.signUpForm.controls['teacherID'].validator = Validators.required;
this.signUpForm.controls['teacherID'].updateValueAndValidity();
this.signUpForm.controls['studentID'].validator = null;
this.signUpForm.controls['studentID'].updateValueAndValidity();
}
else if (selectedGroup == 2) {
this.signUpForm.controls['teacherCode'].validator = null;
this.signUpForm.controls['teacherCode'].updateValueAndValidity();
this.signUpForm.controls['teacherID'].validator = null;
this.signUpForm.controls['teacherID'].updateValueAndValidity();
this.signUpForm.controls['studentID'].validator = Validators.required;
this.signUpForm.controls['studentID'].updateValueAndValidity();
}
}
Run Code Online (Sandbox Code Playgroud)
例如,required仅当teacherCode.value有值时才进行验证:
this.signUpForm.addControl("teacherCode", new Control("",
(c:Control) => {
if(this.signUpForm.controls['teacherID'].value) {
return Validators.required(c);
}
})
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6489 次 |
| 最近记录: |