【问题标题】:how to start and stop the count down timer using ngx-countdown using Angular如何使用 Angular 使用 ngx-countdown 启动和停止倒数计时器
【发布时间】:2020-09-02 11:11:51
【问题描述】:

场景:在这里我正在寻找一个倒计时计时器,其中用户经过几秒钟并且用户为此按下开始或停止 我正在使用 ngx 倒数计时器

要求:

  1. 用户为计时器提供了一些自定义秒数(这已经完成)。
  2. 默认情况下如何显示开始按钮,当用户按下开始按钮时,只需要显示停止按钮。
  3. 我如何在给定秒数结束时停止计时器,我的意思是当用户给定 60 秒时,它应该在此之后停止并显示警报,并且用户也可以停止计时器。

下面是我的代码

  <countdown [config]="{leftTime: timeData}" (event)="handleEvent($event)"></countdown>
  `
})
export class AppComponent  {
  timeData = "120"
  constructor(){

  }

handleEvent(event){
  console.log(event)
}

下面是我的 stackblitz 网址

https://stackblitz.com/edit/ngx-countdown-setup-bwdk4s?file=src/app/app.component.ts

【问题讨论】:

    标签: javascript angular countdowntimer


    【解决方案1】:

    您需要添加@ViewChild('cd', { static: false }) private countdown: CountdownComponent;

    然后添加一些按钮并绑定动作:

    模板:

    <countdown #cd [config]="{leftTime: timeData}" (event)="handleEvent($event)"> 
    </countdown>
    <button (click)="pause()">pause</button>
    <button (click)="start()">start</button>
    

    功能:

    pause(){
      this.countdown.pause();
    }
    
    start(){
      this.countdown.begin();
    }
    

    示例: https://stackblitz.com/edit/ngx-countdown-setup-qo8kfq?file=src%2Fapp%2Fapp.component.ts

    编辑:

    在配置中添加“通知”属性:

    [config]="{leftTime: timeData, notify: [ 2, 5 ]}"
    

    那么当定时器达到 5 & 2 时,将触发通知事件

    handleEvent(event){
        if(event.action === 'notify'){
          console.log('Hi!');
        }
      }
    

    示例: https://stackblitz.com/edit/ngx-countdown-setup-qo8kfq?file=src%2Fapp%2Fapp.component.ts

    【讨论】:

    • 好的,但是如何在给定的秒数完成后显示警报?就像我在 20 秒后给了 20 秒一样,它应该会触发一种警报
    • @Madpop 立即尝试
    • 是的,你在这里提到了 2,5,但在实际场景中,当用户按下停止时,我们必须知道正确的确切值
    • @izik 暂停倒计时后如何获取剩余时间?
    【解决方案2】:

    这可能对你有帮助

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
      <countdown [config]="config" (event)="handleEvent($event)"></countdown>
      <button (click)="start()">START</button>
      <button *ngIf="showStop" (click)="stop()">STOP</button>
      `
    })
    export class AppComponent  {
      timeData = "60"
      config:any;
      showStop:boolean;
      constructor(){
    
      }
        public ngOnInit() {
          this.config = {leftTime: this.timeData, demand:true};
      }
    start(){
      this.config = {leftTime:this.timeData, demand:false};
      this.showStop=true;
    }
    stop(){
       this.config = {leftTime:this.timeData, demand:true};
       this.showStop=false;
    }
    handleEvent(event){
      console.log(event)
    }
    }
    

    【讨论】:

    • 好的,但是如何在给定秒数完成后显示警报?就像我在 20 秒后给了 20 秒一样,它应该触发一种警报
    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多