How to manually trigger Button Click?


#1

Hi there, second post today, next problem. I’d like to trigger a manually clickevent on an ionic.button, but as soon as you add the “ion-button” attribute, you get the error “Cannot read property ‘dispatchEvent’ of undefined”?!

sample code below:
Snippet from page.html
<button ion-button #mybutton (click)=“onClick()”>test //not working
<button #mybutton (click)=“onClick()”>test //working

snippet from page.ts
public onClick() {
let event = new MouseEvent(‘click’, { bubbles: true });
this.renderer.invokeElementMethod(
this.mybutton.nativeElement, ‘dispatchEvent’, [event]);
}
Any ideas?


#2

And this is why I develop on typescript.

on .html
<button (click) = "onClick ()">Button</button>

on .ts
(function)

onClick () {
  //you can do whatever you want here!'
}

#3

Are you serious? My example is in typescript! These are only snippets. My god…


#4

Thought it was chinese. Did it work?


#6

Hi Mica,

Did you find the solution for this? I have a problem to which this seems to be a solution.

Thanks!


#7

Hey @SMhassan

Just use vanilla Javascript:

document.getElementById(‘yourId’).click();


#8

Thanks, was just wondering if there was an angular way to do it.


#9

I have tried this, but with no success - the click event works fine using “ionic serve” but not in the emulator and ionic.view.
Any ideas ?


#10

I encounter this problem too
cant do it in ios device
but I find out that if you add delay more than 2500ms like this

setTimeout(function () {
      document.getElementById('mainBtn').click();
    }, 2500);

It will be ok

Anyone can help here?


#11

Don’t use setTimeout() in app code. It will produce inconsistent results. Don’t access the DOM directly in app code. That’s Angular’s territory. Leave it alone.

The only situation in which you should even try to do something like “manually trigger button click” is in testing, and in that case, you can use this function (which I think I cribbed out of the Angular source):


export function click(el: DebugElement | HTMLElement, eventObj: any = ButtonClickEvents.left): void {
  if (el instanceof HTMLElement) {
    el.click();
  } else {
    (<any>el).triggerEventHandler('click', eventObj);
  }
}