Search code examples
angularangular2-formsangular2-changedetection

Angular 2 forms + OnPush


I am writing an angular 2 application where I try to use ChangeDetectionStrategy.OnPush everywhere, for performance reasons. I have a complex component that needs OnPush in order to work smoothly, which contains another component that is displaying a form (created with FormBuilder). I now noticed that when I click on a slider, the internal value of it is updated (i.e. form.value), but the slider component does not visualize this new value, i.e. it is stuck at the old position.

My first idea to fix this, was to set the leaf component's change detection strategy to DEFAULT, but this had no effect as apparently this requires changing the change detection strategy of its parent components too (which is not possible in my application).

Then I came up with this idea:

@Component({
   ...
})
class MyComponent implements OnInit {
  constructor(private zone: NgZone) {}

ngOnInit() {
  INIT_FORM();

  this.form.valueChanges
    .subscribe(() => {
      this.zone.run(() => {});
    });
  }
}

but it has no effect.

Is there any possibility to make angular 2 forms work inside a component that uses OnPush?


Solution

  • Not tested myself but invoking change detection manually might do what you want:

    @Component({
       ...
    })
    class MyComponent implements OnInit {
      constructor(private cdRef: ChangeDetectorRef) {}
    
    ngOnInit() {
      INIT_FORM();
    
      this.form.valueChanges
        .subscribe(() => {
          this.cdRef.detectChanges();
        });
      }
    }