Angular 4有条件地删除所需的验证器 [英] Angular 4 remove required validator conditionally

查看:357
本文介绍了Angular 4有条件地删除所需的验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 4应用中,我有一个这样的表单模型:

In Angular 4 app I have a form model like this:

this.form = this._fb.group({
    title: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]],
    description: ['', [Validators.required, Validators.minLength(3)]]
});

现在,我要从控件验证器数组中动态删除仅所需的验证器.像这样:

Now what I want is to remove dynamically only the required validator from the control validators array. Something like this:

saveDraft() {
    this.form.controls['title'].removeValidator('required'); //Just a fake implementation for demonstration
}

此问题不是所提到问题的重复项.我的情况有所不同,我只想在不知不觉中删除其他验证器的情况.

This question is not the duplicate of the mentioned question. My case is different I just want to remove the required validator unknowingly the other ones.

推荐答案

如果要添加验证,请尝试此验证.

if you want to add validation try this one.

saveDraft() {
   this.form.get('title').setValidators([Validators.required, Validators.minLength(3)]);
   this.form.get('title').updateValueAndValidity();
}

如果要删除验证器,请尝试使用此验证器.

if you want to remove validators try this one.

saveDraft() {
 this.form.get('title').clearValidators();
 this.form.get('title').updateValueAndValidity();
}

这篇关于Angular 4有条件地删除所需的验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆