在窗口中处理组件的属性。
我有一个组件,当我单击离子 - 梅努标签时,它具有设置为true的enableButtons属性。如果我单击其他任何地方,我希望该属性还原为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 tells me that is undefined
this.enableButtons = false;
}
}
}
async presentModalEliminaItems() {
this.menu.close();
this.enableButtons = true;
}
问题在于函数窗口中的“此”。单击是类型窗口,而不是类型的profilepage。我该如何解决?
解决的:我已经使用了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;
}
});
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;
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果只是
undefined
来自此代码段的问题,则必须将代码移至ngoninit(){} {}
。这是一个运行时问题,即constructor
vsoninit
。您还可以通过将 将 标记添加到您的属性中,告诉Typescript您知道您的属性将在运行时收到值,因此,您也可以将
添加到您的声明属性中,从而跳过严格的检查。例如:
enableButtons!:boolean;
If it is just
undefined
issue from this code snippets, you have to move your code tongOnInit(){}
. It is a runtime issue i.eConstructor
vsOnInit
. You can also add thenon 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;
初始化定义中的属性:
布尔类型将在分配中自动推断。
Initialize the property in your definition:
the boolean type will be inferred automatically with the assignment.