Angular 2 - Countdown timer

前端 未结 2 683
北海茫月
北海茫月 2020-12-14 09:59

I am willing to do a countdown timer in Angular 2 that start from 60 (i.e 59, 58,57, etc...)

For that I have the following:

constructor(){
  Observab         


        
2条回答
  •  旧巷少年郎
    2020-12-14 10:43

    There are many ways to achieve this, a basic example is to use the take operator

    import { Observable, timer } from 'rxjs';
    import { take, map } from 'rxjs/operators';
    
    @Component({
       selector: 'my-app',
       template: `

    {{counter$ | async}}

    ` }) export class App { counter$: Observable; count = 60; constructor() { this.counter$ = timer(0,1000).pipe( take(this.count), map(() => --this.count) ); } }

    A better way is to create a counter directive!

    import { Directive, Input, Output, EventEmitter, OnChanges, OnDestroy } from '@angular/core';
    
    import { Subject, Observable, Subscription, timer } from 'rxjs';
    import { switchMap, take, tap } from 'rxjs/operators';
    
    @Directive({
      selector: '[counter]'
    })
    export class CounterDirective implements OnChanges, OnDestroy {
    
      private _counterSource$ = new Subject();
      private _subscription = Subscription.EMPTY;
    
      @Input() counter: number;
      @Input() interval: number;
      @Output() value = new EventEmitter();
    
      constructor() {
    
        this._subscription = this._counterSource$.pipe(
          switchMap(({ interval, count }) =>
            timer(0, interval).pipe(
              take(count),
              tap(() => this.value.emit(--count))
            )
          )
        ).subscribe();
      }
    
      ngOnChanges() {
        this._counterSource$.next({ count: this.counter, interval: this.interval });
      }
    
      ngOnDestroy() {
        this._subscription.unsubscribe();
      }
    
    }
    

    Usage:

    
       {{ count }} 
    
    

    Here is a live stackblitz

提交回复
热议问题