温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-27 09:00:03 来源:脚本之家 阅读:147 作者:灿灿大王 栏目:web开发

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

countDown = false;
countDowmTime = 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);
   }

3.页面上用方法中的变量来控制按钮的显示效果:

<div > 
   <button nz-button [disabled]="countDown" (click)="getCode($event)">{{showButtonText}}</button> 
..... 
</div>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI