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

后端 未结 9 1666
野的像风
野的像风 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:33

    Adding to Julia Passynkova's answer

    To set validation error in component:

    formData.form.controls['email'].setErrors({'incorrect': true});
    

    To unset validation error in component:

    formData.form.controls['email'].setErrors(null);
    

    Be careful with unsetting the errors using null as this will overwrite all errors. If you want to keep some around you may have to check for the existence of other errors first:

    if (isIncorrectOnlyError){
       formData.form.controls['email'].setErrors(null);
    }
    

提交回复
热议问题