use*_*052 6 dom-events angular
我想以编程方式引发click MouseEvent,例如,从 Angular 组件来模拟鼠标单击。这可能吗?如何实现?我在这里没有找到任何关于此的现有问题。
该DOM元素将是某个元素,例如组件模板中的按钮。
在 Angular 中,您将获得一个ElementRefusing ViewChild。然后您可以致电HTMLElmenent.click()或HTMLElement.dispatchEvent(event)。
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)
}
}
Run Code Online (Sandbox Code Playgroud)
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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13357 次 |
| 最近记录: |