admin管理员组文章数量:1123407
It's the first time that I'm going to use change detection onPush
in my project.
I know that when we use this strategy, Angular will detect changes to input properties by comparing their object references, not their contents.
If I add for example this code in a component using onpush
, Angular is not detecting the change, how can we resolve the problem?
this.boxService.selectedBox$.subscribe((box: Box | null) => {
if (box && box.id && box.id === this.index ) {
this.selected = true;
} else {
this.selected = false;
}
});
Thank you.
It's the first time that I'm going to use change detection onPush
in my project.
I know that when we use this strategy, Angular will detect changes to input properties by comparing their object references, not their contents.
If I add for example this code in a component using onpush
, Angular is not detecting the change, how can we resolve the problem?
this.boxService.selectedBox$.subscribe((box: Box | null) => {
if (box && box.id && box.id === this.index ) {
this.selected = true;
} else {
this.selected = false;
}
});
Thank you.
Share Improve this question edited 9 hours ago marc_s 754k183 gold badges1.4k silver badges1.5k bronze badges asked 13 hours ago Nesrine GHRIBINesrine GHRIBI 232 bronze badges2 Answers
Reset to default 0We can use ChangeDetectorRef
to trigger the change detection manually.
constructor(private cdr: ChangeDetectorRef) {}
this.boxService.selectedBox$.subscribe((box: Box | null) => {
if (box && box.id && box.id === this.index ) {
this.selected = true;
} else {
this.selected = false;
}
// this.cdr.markForCheck();
this.cdr.detectChanges();
});
By using ChangeDetectionStrategy.OnPush, you can tell Angular to only run change detection on a component when its input properties change. with onPush strategy, Angular will only trigger change detection in the following cases:
- When component’s input property changes
- When an event is triggered in the component
You can use markForCheck
if you want to trigger the change detection manually.
constructor(private cdf: ChangeDetectorRef) {}
// ...
this.boxService.selectedBox$.subscribe((box: Box | null) => {
if (box && box.id && box.id === this.index ) {
this.selected = true;
} else {
this.selected = false;
}
this.cdf.markForCheck(); // <--- trigger change detection
});
本文标签: angularTrigger change detection for primitive attributesStack Overflow
版权声明:本文标题:angular - Trigger change detection for primitive attributes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736566035a1944705.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论