Angular ChangeDetectorRef render live data

584 Views Asked by At

I am trying to get live data on angular basic component.

What I expect: HTML rendering auto incremented each 1 second (i.e.: 0, 1, 2, 3, 4, 5 ..etc.)

What I got: HTML rendering: 0 then 1. (incremented once then stopped)

Stackblitz url for demonstration (apologize if url not valid, first time sharing my code): https://stackblitz.com/edit/angular-9-starter-material-jdjcjp?file=src%2Fapp%2Fapp.component.ts

My code:

import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
} from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
import { Observable, BehaviorSubject, combineLatest, timer } from 'rxjs';
import { map, tap } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  item = 0;

  ngOnInit(): void {
    timer(1000)
      .pipe(
        tap(() => {
          this.item++;
          this.cdr.markForCheck();
        })
      )
      .subscribe();
  }
}
2

There are 2 best solutions below

2
On

Use RxJs Interval instead of timer

interval(1000)  // emit every 1000 milliseconds
      .pipe(
        tap(() => {
          this.item++;
        })
      )
      .subscribe();
0
On

Found it:

ngOnInit() {
    return setInterval(() => {
          this.item++;
          this.cdr.markForCheck();
    }, 1000);
}