Angular中setTimeout清空密码输入框失效问题求助
嗨,这个问题我太熟了——核心原因是setTimeout里普通函数的this指向不对!
在你原来的代码里,setTimeout的回调用了普通function(),这个函数里的this会指向全局对象(浏览器环境下是window),而不是你的Angular组件实例。所以你试着清空的this.confirmPassword和this.newPassword,根本不是组件里绑定到输入框的那两个变量,自然看不到效果。
给你三种简单的修复方法,选哪种都可以:
方法1:用箭头函数(最推荐,Angular开发里的常规操作)
箭头函数会自动继承外层上下文的this,也就是你的组件实例,直接替换掉普通函数就行:
changePasswordResult(success: boolean) { this.passwordUpdated = success; if (success) { setTimeout(() => { // 这里改成箭头函数 this.confirmPassword = ''; this.newPassword = ''; }, 15000); } }
方法2:提前保存组件的this到变量
在setTimeout外面先把组件的this存成一个变量,比如self或者that,然后在回调里用这个变量访问组件属性:
changePasswordResult(success: boolean) { this.passwordUpdated = success; if (success) { const self = this; // 先把组件的this存起来 setTimeout(function() { self.confirmPassword = ''; self.newPassword = ''; }, 15000); } }
方法3:用bind()绑定this
给普通函数绑定组件的this,强制让回调里的this指向组件实例:
changePasswordResult(success: boolean) { this.passwordUpdated = success; if (success) { setTimeout(function() { this.confirmPassword = ''; this.newPassword = ''; }.bind(this), 15000); // 绑定组件的this } }
另外顺便提个小细节:你模板里的两个输入框name都是newPsw,第二个应该改成confirmPsw,而且第二个的[(ngModel)]应该绑定到confirmPassword吧?不然两个输入框会共用同一个变量,逻辑上也不对,修正后大概是这样:
<input tabindex="5" type="password" class="form-control" name="newPsw" [(ngModel)]="newPassword" (ngModelChange)="checkPassword()"> <input tabindex="5" type="password" class="form-control" name="confirmPsw" [(ngModel)]="confirmPassword" (ngModelChange)="checkPassword()">
内容的提问来源于stack exchange,提问作者user9224039
相关产品推荐
相关产品推荐

