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?
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);
}
}
Yeah but there’s a problem, how would we get the reference of the element to send into the function? It needs to know what element to perform click on. I’ve tried couple ways to get the reference but it never works correctly.
For instance, in an event, if we console.log the event.target this is what we get
we get legit the element itself, I’ve tried so many things but I never managed to get a reference of the element in the code like what event.target does
Is there any way to do this?