Ionic 窗口中组件的句柄属性,onclick

mutmk8jj  于 2022-12-09  发布在  Ionic
关注(0)|答案(2)|浏览(112)

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;
    }
  });
mrfwxfqh

mrfwxfqh1#

如果这段代码片段只是undefined问题,您必须将代码移到ngOnInit(){}。这是一个运行时问题,即ConstructorOnInit。您还可以通过将!标记附加到属性,将non null assertion operator添加到已声明的属性中。告诉TypeScript您知道您的属性将在运行时接收值,从而跳过严格的检查。例如:enableButtons!: boolean;

db2dz4w8

db2dz4w82#

初始化定义中的属性:

export class ProfilePage implements OnInit {
  enableButtons = false;

  ...
}

布尔类型将自动地与赋值一起推断。

相关问题