Angular:如何以编程方式触发 DOM 事件,例如鼠标单击?

use*_*052 6 dom-events angular

我想以编程方式引发click MouseEvent,例如,从 Angular 组件来模拟鼠标单击。这可能吗?如何实现?我在这里没有找到任何关于此的现有问题。

DOM元素将是某个元素,例如组件模板中的按钮。

Chr*_*ert 5

在 Angular 中,您将获得一个ElementRefusing 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)
  }
}
Run Code Online (Sandbox Code Playgroud)

选项 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)
  }
}

Run Code Online (Sandbox Code Playgroud)