skip to Main Content

Trying to figure out why OnPush change detection strategy is not working In this demo.

If I understand correctly OnPush change detection should be triggered when a property reference changes. and in order to ensure this a new array is set each time like this:

    this.periodData$.subscribe((pd) => {
      this.periodData = [...pd];
    });

And the template that renders periodData looks like this:

<div *ngFor="let p of periodData">{{p}}</div>

The periodData is changed via the select control in the demo.

We can see that it is changing via the log, however the template is not updating. If change detection is set to default then it works.

Thoughts?

2

Answers


  1. Chosen as BEST ANSWER

    Ah - OK - I found the answer here. In short:

    Object changes do not trigger on push change detection, that is only true for component inputs.


  2. Use ChangeDetectorRef to manually trigger change detection after updating periodData.

    import {
      ChangeDetectionStrategy,
      Component,
      Input,
      OnInit,
      ViewEncapsulation,
      ChangeDetectorRef,
    } from '@angular/core';
    import { AsyncPipe, NgFor } from '@angular/common';
    import { Observable } from 'rxjs';
    
    @Component({
      selector: 'app-detect',
      imports: [NgFor, AsyncPipe],
      standalone: true,
      template: `
     <div *ngFor="let p of periodData">{{p}}</div>
      `,
      encapsulation: ViewEncapsulation.None,
      changeDetection: ChangeDetectionStrategy.OnPush,
    })
    export class DetectComponent implements OnInit {
      @Input()
      periodData$!: Observable<any[]>;
      periodData: any[] = [];
    
      constructor(private cdr: ChangeDetectorRef) {}
    
      ngOnInit() {
        this.periodData$.subscribe((pd) => {
          console.log(`Period Data is ${JSON.stringify(pd)}`);
          this.periodData = [...pd];
          this.cdr.detectChanges();
        });
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search