Angular为什么我们在detectChanges工作时需要markForCheck

时间:2018-04-25 19:20:40

标签: angular angular2-changedetection

我正在阅读this文章,其中有一节介绍何时使用markForChange()

在他的例子中,他有以下部分:

@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();
    });
  }
}

他使用markForCheck()方法来更新视图。我不明白的是,当markForCheck() 的来电也在更新视图时,为什么我们需要在detectChanges()使用{?}}?

我在StackOverflow上阅读了问题的答案 - What's the difference between markForCheck() and detectChanges()?

但它不符合上面的例子。那么,为什么不拨打detectChanges()而不是markForCheck()

1 个答案:

答案 0 :(得分:0)

markForCheck将向组件要检查其更新视图的父节点(根)发出信息。并且该组件的子代可能不会更新。

detectChanges将检查更新组件及其子组件的视图。因此,与markForCheck

相比,这种方法需要更多的精力