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

6
我希望能够通过编程方式触发一个click MouseEvent事件,例如,从Angular组件中模拟鼠标单击。这是否可能?如何实现?我在这里没有找到任何现有的问题。 DOM元素将是组件模板中的某些元素,例如按钮。

请再给我一些踩的评价,同时解释一下原因。 - user2599052
1
这个问题在 Stack Overflow 上已经被问过,涉及到原生 JavaScript,但没有涉及到 Angular 的上下文。这是一个有效的问题。 - Christopher Peisert
1个回答

5
在Angular中,您可以使用ViewChild获取ElementRef。然后,您可以调用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)
  }
}


组件的 ts 文件中是否可用文档对象? - user2599052
即使提供为全局对象,使用它是一个好的实践吗? - user2599052
一个重要的点是,我尝试过了,但我没有看到它与Angular变更检测一起工作。也许原生元素触发的操作被忽略了... - user2599052
请告诉我您是否想查看代码片段?事件已触发并调用了事件处理程序,但是在事件处理程序内部,我更改了一个属性,因此模板应该已更改,但实际上没有。 - user2599052

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接