gpt4 book ai didi

Angular2 RC : Added controls with addControls method after creation of the ControlGroup is not working

转载 作者:太空狗 更新时间:2023-10-29 17:39:53 24 4
gpt4 key购买 nike

我有一个添加不同字段的来源(我正在添加新控件,因为只是使用 *ngIf 将它们从模板中隐藏不会将它们从表单中排除,因此导致表单无效)基于选择选项中的所选选项.我正在使用 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;
}
}

看起来 angular 无法识别这些新字段。我认为它与 AbstractControl 有关,但文档中缺少相关内容。这是问题的快照,动态添加的控件没有被 Angular 拾取。 enter image description here

为了展示这个问题,我在下面的 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();

}
}

最佳答案

例如,仅当 teacherCode.value 具有值时才执行 required 验证:

    this.signUpForm.addControl("teacherCode", new Control("", 
(c:Control) => {
if(this.signUpForm.controls['teacherID'].value) {
return Validators.required(c);
}
})
);

关于Angular2 RC : Added controls with addControls method after creation of the ControlGroup is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37490663/

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