I want to raise a click
MouseEvent programmatically, for example, from an Angular Component to simulate a mouse click. Is this possible and how? I didn't find any existing question on this here.
The DOM
element will be some element like a button in a Component template.
In Angular, you would obtain an ElementRef
using ViewChild
. Then you could either call HTMLElmenent.click()
or HTMLElement.dispatchEvent(event)
.
See Stackblitz Demo
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core'
@Component({
selector: 'my-app',
template: `
<h1>Test Angular Programmatic Click Event</h1>
<div #namedElement (click)="showAlert('Clicked namedElement')">
Named element
</div>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChild('namedElement', {static: false}) namedElement: ElementRef;
public constructor() {}
ngAfterViewInit() {
this.namedElement.nativeElement.click();
}
public showAlert(msg: string) {
alert(msg)
}
}
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core'
@Component({
selector: 'my-app',
template: `
<h1>Test Angular Programmatic Click Event</h1>
<div #namedElement (click)="showAlert('Clicked namedElement')">
Named element
</div>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChild('namedElement', {static: false}) namedElement: ElementRef;
public constructor() {}
ngAfterViewInit() {
const event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
this.namedElement.nativeElement.dispatchEvent(event);
}
public showAlert(msg: string) {
alert(msg)
}
}