Search code examples
angularkeypress

JQuery Trigger equivalent in Angular2 or higher


Hi all As I was aware of trigger() method in JQuery for triggering the event manually, I want to know that is there any equivalent method in Angular2 or higher. Recently I have a textarea in which a text variable is bind from the typescript now whenever the variable's value changes from typescript I want to fire keypress event of textarea.

Here are my code

 <textarea  rows="3" id='myInputText'  class="form-control textareaPage" 
  name="businessQuery" [(ngModel)]="text" #textarea (input)="addTags(); getContectualHelp()" #queryEditor="ngModel" taxonomyValidate ngModel required [attr.arrayIncludes]="listOfTaxonomy" placeholder="Please type query to search" style="border-radius: 0; min-height:70px;"> </textarea>

And the method which loads text in textarea is as follows

 loadQuery(event) {
 this.text = event.target.innerText;
 }

I want to manually trigger keypress event while loading text into textarea by this method loadQuery(event).


Solution

  • Use ViewChild with a template variable to get a reference to the textarea, then use the Renderer to invoke dispatchEvent to fire the event:

     @ViewChild('textarea') textarea:ElementRef;
    
    loadQuery() {
     let event = new MouseEvent('click', {bubbles: true});
     this.renderer.invokeElementMethod(this.textarea.nativeElement, 'dispatchEvent', [event]);
     }