简体   繁体   English

Angular 4:禁用嵌套表单验证器

[英]Angular 4: Disabling nested form validators

I want to disable the "addressLine1" validator; 我想禁用“addressLine1”验证器; how can i disable it? 我怎么能禁用它? seeing at it is nested inside of "address" element 看到它嵌套在“地址”元素内

 this.form = fb.group({           
            'region': [null, Validators.required],

            'address': fb.group({               
                'addressLine1': ["", Validators.required],
                'addressLine2': [""],
                'city': ["", Validators.required]             
            }),

        })

I tried this below but it did not work 我在下面尝试了这个,但它没有用

 this.form.controls["address"]["addressLine1"] .disable();

Thank you 谢谢

Here is the html: 这是html:

<form [formGroup]="form">

<div ><label><span class="required">*</span>State/Province/Region<br><input class="form-control" pInputText formControlName="addressLine1" [(ngModel)]="selected.address.addressLine1" required></label></div>

</form>

The correct syntax should be: 正确的语法应该是:

(this.form.controls["address"] as FormGroup).controls["addressLine1"].disable({});

or even better 甚至更好

this.form.get('address.addressLine1').disable();

Stackblitz example Stackblitz的例子

Update 更新

To disable validator use the following code: 要禁用验证器,请使用以下代码:

const control = this.form.get('address.addressLine1');
control.setValidators(null);
control.updateValueAndValidity();

Stackblitz Example Stackblitz示例

We need to pass parameters to disable method as docs says us: 我们需要将参数传递给disable方法,因为docs告诉我们:

在此输入图像描述

So if you don't need to pass any parameters, just pass an empty object, and the code should look like this: 因此,如果您不需要传递任何参数,只需传递一个空对象,代码应如下所示:

this.form.controls["address"]["addressLine1"].disable({});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM