I have a component where I have the enableButtons property that is set to true when I click on an ion-menu label. I would like if I click anywhere else this property to revert to false. I tried this piece of code:
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 tells me that is undefined
this.enableButtons = false;
}
}
}
async presentModalEliminaItems() {
this.menu.close();
this.enableButtons = true;
}
The problem is that "this" in the function window.onClick is of type Window and not of type ProfilePage . How can I solve it ?
SOLVED : i have used the class Renderer2 of Angular instead of window.onclick:
@ViewChild('aEliminaVideo') toggleButton: ElementRef;
this.renderer.listen('window', 'click',(e:Event)=>{
if(e.target!==this.toggleButton.nativeElement && this.enableButtons == true){
this.enableButtons = false;
}
});
2条答案
按热度按时间mrfwxfqh1#
如果这段代码片段只是
undefined
问题,您必须将代码移到ngOnInit(){}
。这是一个运行时问题,即Constructor
与OnInit
。您还可以通过将!
标记附加到属性,将non null assertion operator
添加到已声明的属性中。告诉TypeScript您知道您的属性将在运行时接收值,从而跳过严格的检查。例如:enableButtons!: boolean;
db2dz4w82#
初始化定义中的属性:
布尔类型将自动地与赋值一起推断。