1

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

2
  • perhaps you could manually set the myForm.valid prop to false in this case. Commented Jun 13, 2019 at 16:28
  • 1
    I would suggest reactive form instead :) Commented Jun 13, 2019 at 16:43

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, I should start thinking about migrating to Reacive Forms...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.