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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Android-View点击事件短时间重复点击的过滤
- 手动升级Coreos版本
- mongodb操作的模块手动封装
- 越狱手记:手动编译安装 Electra
- 从零手动实现简易Tomcat
- 手动实现一个速度仪表盘
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Learning PHP, MySQL, JavaScript, and CSS
Robin Nixon / O'Reilly Media / 2012-9-3 / USD 39.99
If you're familiar with HTML, you can quickly learn how to build interactive, data-driven websites with the powerful combination of PHP, MySQL, and JavaScript - the top technologies for creating moder......一起来看看 《Learning PHP, MySQL, JavaScript, and CSS》 这本书的介绍吧!