1
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)

Billu
  • 2,733
  • 26
  • 47

2 Answers2

1

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
Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74
  • I would opt for the custom validator. Just removing errors means, that all other types of validation errors you may have added (like a minimum length), would be removed too. – JanRecker Jun 11 '21 at 06:16
  • @JanRecker Not entirely true. If you check I have applied the validator on the `addForm`. So only that FormGroup is affected. The children formGroup are not affected, You can check the updated demo. I have added a minLength of 3 – Owen Kelvin Jun 11 '21 at 06:25
  • @OwenKelvin it is working, can you please describe what is "get" before function name "valOfPass()"? – Billu Jun 11 '21 at 09:47
  • `get` here has been used as a `getter` to "get" the property "valOfPass". This was my approach to make the demo work but in your case you may have used a different approach. Also I think you may need to have a look at some articles to understand the concept of "getters and setters" e.g here https://www.w3schools.com/js/js_object_accessors.asp – Owen Kelvin Jun 11 '21 at 09:57
1

The best way to achieve this, is to create a custom validator and use it on the FormGroup({}) itself not on the FormControl() of the password.

This validator directive class takes the two FormControl()s as input and checks for their values if they match or not. So the validator must be on a higher level than the two FormControl()s that it is validating.

I hope this is well informative and helpful for your situation.

here's the example

Ahmed Shehatah
  • 658
  • 5
  • 11