Search code examples
angularchange-detector-ref

Why is my ChangeDetectorRef not updating a list in the view?


I have a simple list in the view with hardcoded data in the contoler:

errorcount.component.html

    ...
    <tr *ngFor="let errorcounter of errorCounterList">
      <td>{{errorcounter.date}}</td>
      <td style="text-align:right;">{{errorcounter.count}}</td>
    </tr>
    ....

errorcount.component.ts

import { Component, OnInit, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

export interface ErrorCounter {
  id: number,
  error_id: number,
  date: string,
  count: number
};

@Component({
  selector: 'app-errorcount',
  templateUrl: './errorcount.component.html',
  styleUrls: ['./errorcount.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ErrorcountComponent implements OnInit {

  errorCounterList: ErrorCounter[];

  constructor(private ref: ChangeDetectorRef) {
    this.errorCounterList = [
      { id: 1, error_id: 1, date: '20230101', count: 201 },
      { id: 2, error_id: 2, date: '20230102', count: 321 },
      { id: 3, error_id: 3, date: '20230103', count: 431 },
      { id: 4, error_id: 1, date: '20230104', count: 541 },
      { id: 5, error_id: 2, date: '20230105', count: 651 },
      { id: 6, error_id: 3, date: '20230106', count: 561 },
      { id: 7, error_id: 1, date: '20230107', count: 471 },
      { id: 8, error_id: 2, date: '20230108', count: 381 },
      { id: 9, error_id: 3, date: '20230109', count: 282 },
      { id: 10, error_id: 1, date: '20230110', count: 184 },
    ];
  }

  ngOnInit(): void {
    this.ref.detectChanges();
  }

  filterCounters(id: number) {
    this.errorCounterList = this.errorCounterList.filter(f => f.error_id == id);
    this.ref.markForCheck();
  }

}

I call filterCounters() and the debugger shows thr filtered list but the detectChanges does not change the items in the view.

Any help would get me sleeping again.


Solution

  • To whom it may help, the only way I got this to work was to use LocalStorage:

    ngOnInit(): void {
        localStorage.setItem('errorCounterList', JSON.stringify(this.errorCounterList));
    }
    filterCounterList(id: number) { 
        localStorage.removeItem('errorCounterList');localStorage.setItem('errorCounterList',JSON.stringify(this.errorCounterList.filter(f => f.error_id == id)));
    }
    getCounterList() {
        this.errorCounterList = JSON.parse(localStorage.getItem('errorCounterList') ?? '');
        return this.errorCounterList;
    }
    

    That solved my imidiate problem, but it will not always fit as a solution.