如何使用反应式表单添加动态验证

问题描述 投票:1回答:2

我想在动态生成的字段上添加验证。这是我的代码。

projectForm: FormGroup;

constructor(private sanitizer:DomSanitizer,private router: Router,private fb: FormBuilder,private projectService: ProjectService,private fnService:FunctionsService, private  userService : UserService) {      

    this.projectForm = fb.group({
        'shirnkrap':[null, Validators.required],
        'cd_text':[null, Validators.required],
        'assignto':[null, Validators.required],
        'projecttype':[null, Validators.required]

    });
}

在一个函数上我想添加新的验证,它将触发<select>change事件。

我试试这个,

this.projectForm.controls['project_name'].setValidators([Validators.required]);,但它给了我这个错误,

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'setValidators' of undefined

那么有人可以帮助我如何添加验证?

angular validation angular-reactive-forms
2个回答
1
投票

您的问题不完全是在表单中添加验证器。它更多地动态地向表单添加控件。

不幸的是,看起来这不是用addControl方法可行的东西。根据documentation,您只应在实例化表单时使用addControl()

那么,如何处理动态控件呢? 2件事是可行的:第一件看起来太复杂的将是使用FormArray。有关更多信息,请查看此答案:How to dynamically add and remove form fields in Angular 2

第二个是直接使用动态字段初始化表单:

this.projectForm = fb.group({
    'shirnkrap':[null, Validators.required],
    'cd_text':[null, Validators.required],
    'assignto':[null, Validators.required],
    'projecttype':[null, Validators.required],
    'project_name': ''
});

在您的模板中,您只需要根据您的条件隐藏该字段(使用ng-if="my-selected-value === 'someValue'"

然后,在你的<select>更改,你将不得不添加你的验证器:

if(my-selected-value === 'someValue') {
    this.myForm.controls["firstName"].setValidators([Validators.required]);
    this.myForm.updateValueAndValidity();
}

不要忘记更新表单的有效性。否则,您必须等待用户更新字段,然后才能看到您的表单无效。

你可以在Deborah Kurata的Reactive Form教程中看到一个例子:


-3
投票

使用以下代码动态添加验证:

this.myForm.controls["firstName"].setValidators([Validators.required]);

您的formGroup对象没有project_name字段。您还可以在formgroup对象中动态添加formcontrol。

this.projectForm.addControl("project_name", new FormControl(null));

希望它会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.