angular2手动点击特定元素上的点击事件

栏目: JavaScript · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/36639486/angular2-manually-firing-click-event-on-particular-element

我试图在元素上编程点击点击事件(或任何其他事件),换句话说,我想知道在angular2中由jQuery .trigger()方法提供的类似功能.

有没有内置的方法来做到这一点? …..如果不是,请建议我该怎么做

考虑以下代码片段

<form [ngFormModel]="imgUploadFrm"
          (ngSubmit)="onSubmit(imgUploadFrm)">
        <br>
        <div class="input-field">
            <input type="file" id="imgFile" (click)="onChange($event)" >
        </div>
        <button id="btnAdd" type="submit" (click)="showImageBrowseDlg()" )>Add Picture</button>
 </form>

这里当用户点击btnAdd它应该触发imgFile上的点击事件

Angular4

代替

this.renderer.invokeElementMethod(
        this.fileInput.nativeElement, 'dispatchEvent', [event]);

使用

this.fileInput.nativeElement.dispatchEvent(event);

因为invokeElementMethod不再是渲染器的一部分.

Angular2

使用 ViewChild 与模板变量来获取对文件输入的引用,然后使用 Renderer 调用dispatchEvent来触发事件:

import { Component, Renderer, ElementRef } from '@angular/core';
@Component({
  ...
  template: `
...
<input #fileInput type="file" id="imgFile" (click)="onChange($event)" >
...`
})
class MyComponent {
  @ViewChild('fileInput') fileInput:ElementRef;

  constructor(private renderer:Renderer) {}

  showImageBrowseDlg() {
    // from http://stackoverflow.com/a/32010791/217408
    let event = new MouseEvent('click', {bubbles: true});
    this.renderer.invokeElementMethod(
        this.fileInput.nativeElement, 'dispatchEvent', [event]);
  }
}

更新

由于Angular团队不再劝阻直接的DOM访问,所以也可以使用更简单的代码

this.fileInput.nativeElement.click()

参见 https://developer.mozilla.org/de/docs/Web/API/EventTarget/dispatchEvent

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/36639486/angular2-manually-firing-click-event-on-particular-element


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms of the Intelligent Web

Algorithms of the Intelligent Web

Haralambos Marmanis、Dmitry Babenko / Manning Publications / 2009-7-8 / GBP 28.99

Web 2.0 applications provide a rich user experience, but the parts you can't see are just as important-and impressive. They use powerful techniques to process information intelligently and offer featu......一起来看看 《Algorithms of the Intelligent Web》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器