gpt4 book ai didi

Angular 为什么我们需要 markForCheck 当 detectChanges 也有效时

转载 作者:行者123 更新时间:2023-12-04 14:00:12 24 4
gpt4 key购买 nike

我正在阅读 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()方法来更新 View 。我不明白的是为什么我们需要使用 markForCheck()在这里拨打 detectChanges() 也在更新 View ?

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

但它不符合上面的例子。那么,何不拨打 detectChanges()相反 markForCheck() ?

最佳答案

markForCheck将信息发送到组件想要检查更新 View 的父节点(到根)。并且组件的子组件可能不会更新。detectChanges将检查更新组件及其子组件的 View 。所以这种方式需要比markForCheck更多的努力

关于Angular 为什么我们需要 markForCheck 当 detectChanges 也有效时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com