Change detection does not trigger when the formgroup values change

前端 未结 4 627
我在风中等你
我在风中等你 2021-01-11 19:12

I have created a simple example to demonstrate a weird issue I\'m facing.

Stackblitz - https://stackblitz.com/edit/angular-change-detection-form-group

I hav

4条回答
  •  心在旅途
    2021-01-11 20:03

    You could do something better !, let me know if this works :

    when you use reactive forms you can use a really cool method called updateValueAndValidity();

    private changeControlValue(control, value: number) {
        control.setValue(value);
        control.updateValueAndValidity();
      }
    

    You can also use this method when updating the validators added to a form, example:

    this.control.setValidators([Validators.required, Validators.minLength(5)]);
    control.updateValueAndValidity();
    

    This should do the trick ! I think this is one of the best adventages of using reactive forms or form controls against ng-model.

    I don't recommend to use valueChanges at your form as you are open to forget to de-subscribe and create a memory leak, even you remember it can be tedious to create this flow.

    And remember, when using onPush change detection only three things are going to be detected as changes by Angular:

    1- Inputs and Outputs. 2- Html events that the user can do, like (click). 3- Async events like subscriptions.

    I hope i helped you !.

提交回复
热议问题