我希望能够通过编程方式触发一个
click
MouseEvent事件,例如,从Angular组件中模拟鼠标单击。这是否可能?如何实现?我在这里没有找到任何现有的问题。
DOM
元素将是组件模板中的某些元素,例如按钮。click
MouseEvent事件,例如,从Angular组件中模拟鼠标单击。这是否可能?如何实现?我在这里没有找到任何现有的问题。
DOM
元素将是组件模板中的某些元素,例如按钮。ViewChild
获取ElementRef
。然后,您可以调用HTMLElmenent.click()
或HTMLElement.dispatchEvent(event)
。请参见Stackblitz演示。
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)
}
}