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 every property of the this object is undefined. How can I solve it ?
CodePudding user response:
If it is just undefined
issue from this code snippets, you have to move your code to ngOnInit(){}
. It is a runtime issue i.e Constructor
vs OnInit
. You can also add the non null assertion operator
to your declared properties by attaching !
mark to your properties, telling TypeScript that you know that your properties will recieve value at runtime and thus skip strict checking.
Such as: enableButtons!: boolean;
CodePudding user response:
Initialize the property in your definition:
export class ProfilePage implements OnInit {
enableButtons = false;
...
}
the boolean type will be inferred automatically with the assignment.