【问题标题】:Listen when button pressed按下按钮时收听
【发布时间】:2017-03-03 17:01:03
【问题描述】:

我已经阅读了关于 on-click() 的信息,但我正在寻找的不是 wath。 我需要从一个函数访问 dom 并查看按钮是否被按下。我听说过 ElementRef,但不知道如何使用它。我还看到我使用的某些类(如谷歌地图上的标记)使用 addEventListener。

这是打字稿中的准确代码吗? :

cursorDom.addEventListener("change", event => {
  console.log("change");
  if(document.getElementById('cursor').style.visibility=='visible'){
    console.log("visible");
  }else{
    console.log("invisible");
  }
});

编辑:

我整天都在理解 wath 相当于 addEventListener (renderer, elementRef, Viewchild...) 它变得越来越模糊。我想要做的只是一个 eventListener 来检查 div 是否可见,但其中没有 todo 函数。我发现的最接近的是:

this.renderer.listen(this.elementRef.nativeElement, 'click', () => { /* callback */ });

但没能解决这个问题。

假设我有一个函数,如果我有所有的 init,我的 Googlemarker 是在其中创建的可见或不可见。

编辑 2:

在空白页上测试。

html:

<div id="cursor" #cursor [style.display]="isVisible ? 'inline' : 'none'"></div>

打字稿:

import { Component, ViewChild, Renderer } from '@angular/core';
import { NavController } from 'ionic-angular';


@Component({
 selector: 'page-signup',
 templateUrl: 'signup.html'
})

export class SignupPage {
   @ViewChild('cursor') myDiv;
   constructor(public navCtrl: NavController, renderer: Renderer) {
       renderer.listen(this.myDiv, 'change', event => console.log(event));
}

 ionViewDidLoad() {
   console.log('Hello Signup Page');
 }
}

错误:

 Cannot read property 'addEventListener' of undefined

【问题讨论】:

    标签: angular typescript ionic2


    【解决方案1】:

    您可以使用 ViewChild 装饰器来获取您想要的任何元素:

    @Component({
      selector: 'my-app',
      template: `
       <div #myDiv>Div</div>
      `,
    })
    export class App {
      @ViewChild('myDiv') myDiv;
    
    
      ngAfterContentInit() {
        // This is the native element, do whatever you want
        console.log(this.myDiv.nativeElement)
      }  
    
    }
    

    【讨论】:

    • 抱歉,我已经对此进行了测试,但看不到它如何替换 eventListener。我整天都在理解 wath 相当于 addEventListener (renderer, elementRef, Viewchild ...) 它变得越来越模糊。我想做的只是一个 eventListener 来检查 div 是否可见,但里面没有 todo 函数。
    • 尝试编辑您的问题并更好地解释,因为我们并不真正了解您想要完成什么。
    【解决方案2】:

    好吧,如果你需要添加一个事件监听器和一个回调有一个HostListener 模块:

    @HostListener('window:click', ['$event'])
    callback(event) {}
    

    【讨论】:

    • 我如何标记一个 div 并通过 hostlistener 查看它是否可见?我查看了一些示例,但仍然无法弄清楚如何使用 id 定位元素:christianliebel.com/2016/05/…
    • 好的。我明白。 Hostlistener 我们这里不合适。您可能需要使用绑定到目标元素的 ViewChild 或组件属性 [hidden]
    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    相关资源
    最近更新 更多