Understanding change detection in angular 2

前端 未结 2 417
一向
一向 2021-01-21 10:13

I have come across below example in Angular 2 documentation

@Component({
  selector: \'cmp\',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `Num         


        
相关标签:
2条回答
  • 2021-01-21 10:31

    Using ChangeDetectionStrategy.OnPush tells Angular not to perform change detection on your component (i.e. updating its view) unless one or more of the component's inputs has changed (these inputs should be immutable objects).

    For any events that come from within the component itself and require the view to be updated, you have to explicitly tell the change detector to look for changes in that component on its next change detection run.

    In this snippet, ref is a reference to the change detector. Calling ref.markForCheck() tells the change detector that something has happened that will change the view (i.e. numberOfTicks has been incremented) and it needs to recompute it.

    0 讨论(0)
  • 2021-01-21 10:40

    With ChangeDetectionStrategy.OnPush Angular runs change detection, when in @Input() was updated, a DOM event Angular listens to was received, or the async pipe (| async) received a new value.

    If you for example subscribe to an observable from a service and update the status of the component, bindings to this status won't be updated, because this is not covered by above list. If you call this.ref.markForCheck() you tell Angular that it should run change detection because there actually are changes that need to be updated (that's also what the async pipe does).

    Other cases are if you explicitly (this.zone.runOutsideAngular()) or for some other reasons code runs outside Angulars zone modifies the status of the component, this also won't be covered (even when the code is an event handler).

    0 讨论(0)
提交回复
热议问题