简体   繁体   English

需要 angular 反应式表单切换验证吗?

[英]angular reactive form toggle validation required?

I have this radio button asking (do you have massage certificate?) if yes it will show the file input.我有这个单选按钮询问(你有按摩证书吗?)如果是,它将显示文件输入。 I want this file input not required be default and if the user select yes it will become required.我希望这个文件输入不是默认的,如果用户 select 是的,它将成为必需的。 I have this code below that set cert validation to null by default and if has has_cert become true then set cert validator but its not working.. I need your help guys.我在下面有这段代码,默认情况下将证书验证设置为 null,如果 has_cert 变为 true,则设置证书验证器但它不起作用..我需要你们的帮助。 Thanks in advance.提前致谢。

<p>Form value: {{ form.value | json }}</p>
<p>cert input : {{ form.get('cert').status | json }}</p>

.ts .ts

form: FormGroup;
has_cert = new FormControl(false || true);
has_exp = new FormControl(false || true);
ngOnInit(): void {

    this.form = new FormGroup({
        ...
        has_cert: new FormControl(''),
        cert: new FormControl(''),
        ...
    })

    this.form.get("cert").setValidators(null);

    this.form.get('has_cert').valueChanges.pipe(
        filter(value => value === false || null)
    ).subscribe(
        () => this.form.get('cert').setValue(''),
        () => this.form.get("cert").setValidators(null)
    );

    this.form.get("has_cert").valueChanges.pipe(
        filter(value => value === true)
    ).subscribe(
        () => this.form.get("cert").setValidators(
            [
                Validators.required,
                Validators.pattern('^.*\.(doc|DOC|docx|DOCX|pdf|PDF)$')
            ]
        )
    );
}

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

You need to use form.get('something').setValidators(...) for each cases.您需要对每种情况使用form.get('something').setValidators(...)

To add to @Liu Zhang's answer, I believe you can use clearValidators to remove all the validators you added with setValidators.要添加到@Liu Zhang 的答案,我相信您可以使用 clearValidators 删除您使用 setValidators 添加的所有验证器。

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

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