I'm trying to program a click-click event (or any other event) on an element, in other words, I'm wondering about similar functionality provided by the jQuery .trigger() method in angular2.
Is there a built-in way to do this? ...If not, please suggest what I should do
Consider the following code snippet
<form [ngFormModel]="imgUploadFrm" (ngSubmit)="onSubmit(imgUploadFrm)"> <br> <div class="input-field"> <input type="file" (click)="onChange($event)" > </div> <button type="submit" (click)="showImageBrowseDlg()" )>Add Picture</button> </form>
Here when the user clicks btnAdd it should trigger the click event on imgFile
Angular4
replace
( , 'dispatchEvent', [event]);
use
(event);
Because the invokeElementMethod is no longer part of the renderer.
Angular2
useViewChild With template variables to get a reference to the file input, and then useRenderer Call dispatchEvent to trigger the event:
import { Component, Renderer, ElementRef } from '@angular/core'; @Component({ ... template: ` ... <input #fileInput type="file" (click)="onChange($event)" > ...` }) class MyComponent { @ViewChild('fileInput') fileInput:ElementRef; constructor(private renderer:Renderer) {} showImageBrowseDlg() { // from /a/32010791/217408 let event = new MouseEvent('click', {bubbles: true}); ( , 'dispatchEvent', [event]); } }
renew
Since the Angular team no longer discourages direct DOM access, simpler code can also be used
()
See/de/docs/Web/API/EventTarget/dispatchEvent
Code Log Copyright Statement:
Translated from:/questions/36639486/angular2-manually-firing-click-event-on-particular-element
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.