5

I am reading this article which has a section on when to use markForChange().

In his example he has the following component:

@Component({
  selector: 'cart-badge',
  template: '{{counter}}',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CartBadgeComponent {

  @Input() addItemStream;

  counter = 0;

  constructor(private cd: ChangeDetectorRef) {}

  ngOnInit() {
    this.addItemStream.subscribe(() => {
      this.counter++;
      this.cd.markForCheck();
    });
  }
}

And he uses the markForCheck() method in order to update the view. The thing that I don't understand is that why we need to use markForCheck() here when a call to detectChanges() is also updating the view?

I read the answer on StackOverflow for the question - What's the difference between markForCheck() and detectChanges()?

But it does not meet the example above. So, why don't call detectChanges() instead markForCheck()?

undefined
  • 6,366
  • 12
  • 46
  • 90
  • 1
    how does it not meet the example above? the answer you linked states that markForChanges is commonly used when you are working with OnPush Strategy, which is what is done here. In this specific case there is not difference between the two. However, while calling markForCheck for example twice within one iteration, will lead to one changeDetection cycle, calling detectChanges twice would cause two of them. – Patrick Kelleter Apr 25 '18 at 20:04
  • Can you give a concrete example, please? – undefined Apr 26 '18 at 04:34
  • 1
    @PatrickKelleter but lets say this component has multiple ancestors wouldn't `markForCheck` cause change detection on all of the ancestors and if one of them don't utilize `OnPush` detection it would cause performance issues, right? – Shyamal Parikh May 23 '18 at 15:46

1 Answers1

0

markForCheck will info to the parent node (to the root) that the component wants to check for updating view. And children of the component may not be updated.

detectChanges will check to update the view of the component and for both it's children component. So this way will need more effort than markForCheck