91K00
91K00

Reputation: 452

Angular validation not sync with HTML validation

I got an issue with Angular validation.

I have a nested modelGroup in a parentForm. In the parentForm there is a max value used in the nested modelGroup as a directive input for maximum value of the zip field.

Example in Stackblitz: https://stackblitz.com/edit/91k00-nested-from-validity

Expected result: Once you change the max value, the max directive evaluate the zip field and invalidate the field, then the modelGroup and the parentForm are invalid too.

enter image description here

Actual result: Once you change the max value, the max directive evaluate the zip field and invalidate the field but the modelGroup and parentForm are still valid.

enter image description here

Could you explain me this behaviour and help me to fix it ? Thanks

Upvotes: 1

Views: 113

Answers (1)

Eliseo
Eliseo

Reputation: 58099

You do not give Angular a break. You change the maxValue, and inmediatly make the update. Use a SetTimeout to make a new cicle

  updateValidity() {
    setTimeout(()=>{
      this.parentForm.controls.address.controls["zip"].updateValueAndValidity();
    })
  }

Futhermore, you need call to function updateValidity when you change the value;

setTo899 () {
    this.maxZipValue = 899;
    this.updateValidity()
  }

And

<input type="number" name="maxZipValue" 
     [ngModel]="maxZipValue" 
     (ngModelChange)="maxZipValue=$event;updateValidity()">

see your forked stackblitz

NOTE: I don't be sure, but using ReactiveForms can be work best and it's possible remove this work-around

Upvotes: 1

Related Questions