我想以编程方式(例如,从“角度组件”中举起一个click
MouseEvent来模拟鼠标单击)。这有可能吗?我在这里没有发现任何现有的问题。
DOM
元素将是某个元素,例如组件模板中的按钮。
答案 0 :(得分:0)
在Angular中,您将使用ElementRef
获得一个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)
}
}
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)
}
}