AntonKad
AntonKad

Reputation: 175

Listen when button pressed

I've read about the on-click() but with is not wath i'm looking for. I need to access to the dom from a function and see if the button is pressed. I heard about ElementRef but could not figure out how to use it. I also saw that some class that i use like the marker on google map use addEventListener.

is this accurate code in typescript ? :

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

Edit:

I've pass all day long to understand wath is the equivalent to addEventListener (renderer, elementRef, Viewchild...) it gets fuzier and fuzier. All i want to do is an eventListener that check if the div is visible are not with a todo function in it. The closest thing i found is this :

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

But didn't managed to work this out.

Let's say that i have a function were i have all my init, my Googlemarker gets created in it i want to set a listener to a div and listen if it is visible are not, and in function of that set the markers to visible or invisible.

Edit 2 :

Test on a blank page.

html:

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

typescript:

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

Error:

 Cannot read property 'addEventListener' of undefined

Upvotes: 1

Views: 1376

Answers (2)

Bazinga
Bazinga

Reputation: 11204

You can use the ViewChild decorator to get any element that you want:

@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)
  }  

}

Upvotes: 1

Yaroslav Grishajev
Yaroslav Grishajev

Reputation: 2137

Well, if you need to add an event listener and a callback there is a HostListener module:

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

Upvotes: 0

Related Questions