欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-10-06 17:24:25
1.组件中定义两个变量,分别用于控制按钮是否可以点击(countdown)和按钮上的倒计时数字(countdowntime): countdown = false...

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 style="text-align:center"> 
   <button nz-button [disabled]="countdown" (click)="getcode($event)">{{showbuttontext}}</button> 
..... 
</div>

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