Angular6 发送手机验证码按钮倒计时效果实现方法

1.组件中定义两个变量,分别用于控制按钮是否可以点击(countDown)和按钮上的倒计时数字(countDownTime):

countDown = false;
countDownTime = 60; // 这里设置倒计时为60S
showButtonText = '发送短信验证码'; // 可以控制动态改变的按钮提示信息

2.写一个获取短信验证码的方法绑定到页面的获取短信验证码按钮上:

getCode(event) { 
 this.validateForm1.controls['phone'].markAsDirty();           // 点击获取验证码要以输入了手机号为前提 
 this.validateForm1.controls['phone'].updateValueAndValidity();
  this.userProvider.doSendSMS ({ phone: this.validateForm1.controls.phone.value }).subscribe(res =>{   // 如果手机号验证通过
     if (res) { 
      this.notice.success('短信验证码已发送!');
      this.sendMessage();   // 调用下面的按钮倒计时的方法
 
        } 
       }); 
   }
 
sendMessage() {   // 发送了短信验证码后触发本方法,开始倒计时 
  this.countDown = true;                // 发送验证码后一分钟内,按钮变成不可点击状态 
  this.showButtonText = '验证码已发送(' +60+ 's)';           // 验证码发送后的初始状态 
  const start = setInterval(() = > { 
     if (this.countDownTime >=0 ) {
        this.showButtonText = '验证码已发送(' + this.countDownTime + 's)';     // 动态的进行倒计时
     } else { 
             clearInterval(start);             // 如果超时则重新发送 
             this.showButtonText = '重新发送'; 
             this.countDown = false;         // 按钮再次变成可点击状态
             this.countDownTime = 60; 
            } 
  }, 1000);
}
posted @ 2020-02-25 10:50  tianyou_songyk  阅读(391)  评论(0编辑  收藏  举报