How can I manually set an Angular form field as invalid?

后端 未结 9 1647
野的像风
野的像风 2020-11-28 01:58

I am working on a login form and if the user enters invalid credentials we want to mark both the email and password fields as invalid and display a message that says the log

9条回答
  •  渐次进展
    2020-11-28 02:39

    In my Reactive form, I needed to mark a field as invalid if another field was checked. In ng version 7 I did the following:

        const checkboxField = this.form.get('');
        const dropDownField = this.form.get('');
    
        this.checkboxField$ = checkboxField.valueChanges
            .subscribe((checked: boolean) => {
                if(checked) {
                    dropDownField.setValidators(Validators.required);
                    dropDownField.setErrors({ required: true });
                    dropDownField.markAsDirty();
                } else {
                    dropDownField.clearValidators();
                    dropDownField.markAsPristine();
                }
            });
    

    So above, when I check the box it sets the dropdown as required and marks it as dirty. If you don't mark as such it then it won't be invalid (in error) until you try to submit the form or interact with it.

    If the checkbox is set to false (unchecked) then we clear the required validator on the dropdown and reset it to a pristine state.

    Also - remember to unsubscribe from monitoring field changes!

提交回复
热议问题