2

I have a Angular Reactive Form built with couple of sub-components, all using OnPush strategy. I have also a simple calculation: quantity * rate = total;

If total is <input formControlName="total" /> then it gets updated out-of-the-box even with OnPush.

But I want to display readonly value like:

<div class="number" >
    {{ form.controls.total.value | number }}
</div>

Indeed, this does not work with OnPush. I have to use ChangeDetectionRef in component:

  constructor(
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit() {
    this.form.get('total').valueChanges.subscribe(data => {
      this.cdr.markForCheck();
    });
  }
}

This works. I am just trying to find a bit more elegant and less verbose solution like some built-in pipe or so.

Thanks

2
  • Does it work with pipe and default change detection strategy? Commented Apr 10, 2020 at 8:06
  • Yes. Default strategy re-evaluates every binding on any event (click, type etc) so yes, expression is re-rendered anytime "total" changes. Commented Apr 10, 2020 at 8:07

1 Answer 1

1

This is how OnPush strategy works. Instead of checking whole component tree for changes everytime user clicks something (anything), it listens only for binding values changes. If you are changing not bound values, you have to say "hey angular, I v changed not bound values, revalidate the component tree" - and this is what ChangeDetectionRef will do for you.

This is a tradeoff between preformance and "must-do-it-yourself"s.

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

2 Comments

got it, thanks! I will try to DIY some pipe / directive that will handle it for me.
But you know, pipe will be invoked on run detection and I think the same applies to the directives (but I am not an expert on that) so its like killing your grandpa without beeing born in the first place paradox. But I can be mistaken, I just didnt have to do such things

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.