В Angular вы получите ElementRef
, используя ViewChild
.Тогда вы можете либо позвонить HTMLElmenent.click()
или HTMLElement.dispatchEvent(event)
.
См. Демонстрация Stackblitz
Вариант 1: Использовать HTMLElement.click ()
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)
}
}
Вариант 2: Использовать HTMLElement.dispatchEvent ()
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)
}
}