Angular2 how do you execute a Component timer inside `ngFor`

I want to make a visual countdown timer. I use this component https://github.com/crisbeto/angular-svg-round-progressbar , which relies on SimpleChangefor delivery changes.current.previousValueand changes.current.currentValue.

Here is the template code

<ion-card  class="timer"
  *ngFor="let snapshot of timers | snapshot"
> 
  <ion-card-content>
    <round-progress 
      [current]="snapshot.remaining" 
      [max]="snapshot.duration"
      [rounded]="true"
      [responsive]="true"
      [duration]="800"
      >
    </round-progress>
</ion-card>

I use this code to trigger change detection angular2

  this._tickIntervalHandler = setInterval( ()=>{
      // run change detection
      return;
    }
    // interval = 1000ms
    , interval
  )

updated (After a lot of testing, I found that the problem is not the exact time I execute, and this question has been modified to reflect this.)

, ngFor 1 . snapshot.remaining (.. ), snapshot.remaining ngFor , :

Expression has changed after it was checked

ngFor, - 10ms.

, ngFor, ?

, SnapshotPipe ngFor . , snapshot "". , pull push.

    // timers.ts
    export class TimerPage {
        // use with ngFor
        snapshots: Array<any> = [];

        constructor(timerSvc: TimerSvc){
            let self = this;
            timerSvc.setIntervalCallback = function(){
                self.snapshots = self.timers.map( (timer)=>timer.getSnapshot()  );
            }
        }

    }


    // timer.html
    <ion-card  class="timer"  *ngFor="let snapshot of snapshots"> 
    <ion-card-content>
        <round-progress 
        [current]="snapshot.remaining" 
        [max]="snapshot.duration"
        [rounded]="true"
        [responsive]="true"
        [duration]="800"
        >
        </round-progress>
    </ion-card>



    // TimerSvc can start the tickInterval
    export class TimerSvc {
        _tickIntervalCallback: ()=>void;
        _tickIntervalHandler: number;

        setIntervalCallback( cb: ()=>void) {
            this._tickIntervalCallback = cb;
        }

        startTicking(interval:number=100){
            this._tickIntervalHandler = setInterval( 
                this._tickIntervalCallback
                , interval
            );
        }
    }
+4
1

toJSON ( string ), timers?

, . toJSON pure (. ). trackBy ngFor. .


public snapshots:any[] = [];

private timers:any[] = [];

setInterval(()=>{
    this.snapshots = this.updateSnapshots(this.timers);
}, 100);

<ion-card  class="timer"
  *ngFor="let snapshot of snapshots"
> 
+2

Source: https://habr.com/ru/post/1669265/


All Articles