Home > Mobile >  Angular ChangeDetectorRef render live data
Angular ChangeDetectorRef render live data

Time:08-09

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

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

What i got: HTML rendring: 0 then 1. (incremented once then stoped)

Stackblitz url for demonstration (appologize if url not valid, first time sharing my code): https://stackblitz.com/edit/angular-9-starter-material-jdjcjp?file=src/app/app.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();
  }
}

CodePudding user response:

Use RxJs Interval instead of timer

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

CodePudding user response:

Found it:

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

}

  • Related