Angular6实现简单的短信验证码发送后倒计时
html部分定义一个按钮,{{showButtonText}}为绑定的按钮文字内容:
<button nz-button [disabled]="countDown" (click)="sendMessage()">
{{showButtonText}}</button>
ts部分定义需要用到的属性:
countDown = false; // 按钮是否可点击
countDownTime = 60; //倒计时
showButtonText = '发送短信验证码'; //按钮文字内容
封装方法,此方法这里直接用于点击事件,若按钮有其他需求,可在其他点击方法内调用:
sendMessage(){
this.countDown = true;
this.showButtonText = '验证码已发送(' + 60 + 's)';
const start = setInterval(() => { //间歇调用计时器,间隔为1000ms
if (this.countDownTime >= 0) {
this.showButtonText = '验证码已发送(' + this.countDownTime-- + 's)';
} else {
clearInterval(start); // 清除计时器
this.showButtonText = '重新发送';
this.countDown = false;
this.countDownTime = 60;
}
}, 1000);
}