Search code examples
angularangular11

Change angular11 form validation status when using FormGroup, FormBuilder and Validators


onblurRePass(event:any){
    this.valOfRePass = this.empProperties.repassword;
    console.log("Pass Val: "+this.valOfPass + " RePass Val: "+this.valOfRePass);

    if(this.valOfPass == this.valOfRePass){
      this.matchPassword = 'matched';
      this.addForm.status = 'VALID'; // need to change this status
    }
    else{
      this.matchPassword = 'unmatched';
      this.addForm.status = 'INVALID';  //need to change this status
    }
  }

Error: Cannot assign to 'status' because it is a read-only property.ts(2540)


Solution

  • You have a few options available.

    1. A form is invalid if it has errors so you can simply use setErrors() to update the form
      onblurRePass() {
        this.valOfRePass = this.empProperties.repassword;
        console.log(
          'Pass Val: ' + this.valOfPass + ' RePass Val: ' + this.valOfRePass
        );
    
        if (this.valOfPass == this.valOfRePass) {
          this.matchPassword = 'matched';
          this.addForm.setErrors(null)
        } else {
          this.matchPassword = 'unmatched';
           this.addForm.setErrors({'mismatched': true})
        }
      }
    

    Sample Demo

    1. The other option is to simply use a custom validator password and confirm password field validation angular2 reactive forms