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 badges
Add a comment  | 

2 Answers 2

Reset to default 0

We 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