Angular ReactiveForm display value OnPush

Viewed 318

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

1 Answers

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.

Related