angular2手动触发特定元素上的click事件 [英] angular2 manually firing click event on particular element
问题描述
我正在尝试以编程方式在元素上触发click事件(或任何其他事件),换句话说,我想知道与angular2中jQuery .trigger()方法提供的功能相似.
有内置的方法可以做到这一点吗? .....如果没有,请建议我该怎么做
I am trying to fire click event (or any other event) on element programatically , In other word I want to know the similar features as offered by jQuery .trigger() method in angular2.
Is there any built in method to do this? ..... if not please suggest how can i do this
考虑以下代码片段
<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
Here when user click the btnAdd it should fire the click event on imgFile
推荐答案
Angular4
代替
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
使用
this.fileInput.nativeElement.dispatchEvent(event);
因为invokeElementMethod
不再是渲染器的一部分.
because invokeElementMethod
won't be part of the renderer anymore.
Angular2
使用 ViewChild 和模板变量来获取对文件输入的引用,然后使用 Renderer 调用dispatchEvent
触发事件:
Use ViewChild with a template variable to get a reference to the file input, then use the Renderer to invoke dispatchEvent
to fire the event:
import { Component, Renderer, ElementRef, ViewChild } 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访问,因此也可以使用更简单的代码
Since direct DOM access isn't discouraged anymore by the Angular team this simpler code can be used as well
this.fileInput.nativeElement.click()
另请参见 https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/dispatchEvent
这篇关于angular2手动触发特定元素上的click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!