解决Angular中window.onclick回调this指向错误无法访问组件属性问题
问题说明
开发组件时定义了enableButtons属性,点击ion-menu标签时该属性会被设置为true,需求是点击页面其他任意区域时将该属性重置为false,最初编写的实现代码如下:
export class ProfilePage implements OnInit { enableButtons: boolean; constructor(private router: Router,private menu: MenuController) { this.enableButtons= false; window.onclick = function(event) { if(this.enableButtons){ // 此处访问this.enableButtons会提示undefined this.enableButtons = false; } } } async presentModalEliminaItems() { this.menu.close(); this.enableButtons = true; }
运行时问题:window.onclick回调函数内的this指向全局Window对象,而非ProfilePage组件实例,访问this.enableButtons时会返回undefined,逻辑无法正常执行。
已验证可行方案
不要直接使用window.onclick绑定事件,改用Angular提供的Renderer2类实现全局点击监听,实现代码如下:
@ViewChild('aEliminaVideo') toggleButton: ElementRef; this.renderer.listen('window', 'click',(e:Event)=>{ if(e.target !== this.toggleButton.nativeElement && this.enableButtons == true){ this.enableButtons = false; } });
该写法用箭头函数定义回调,this会直接继承外层组件实例的上下文,不会出现指向丢失的问题。同时逻辑里加了点击目标校验,点到触发按钮本身时不会重置属性,完全符合交互预期。
内容的提问来源于stack exchange,提问作者sirss
相关产品推荐
相关产品推荐

