How to trigger a click event on child element got as result when using querySelector on native element in angular2/angular4

How to trigger a click event on child element got as result when using querySelector on native element in angular2/angular4
0

#1

I tried the code below but didn’t work. I’m using Angular4. I want to trigger a click event if the input of handle click is not less than 3.

import { Component, OnInit, ElementRef } from '@angular/core';

@Component({
    selector: 'box-frame',
    template: `
            <div>
              <div (click)="handleClick(i)" id="box{{i}}" *ngFor="let i of array"></div>   
            </div>
          `
})
export class BoxFrameComponent implements OnInit {
    array: any = [1, 2, 3, 4, 5, 6];
    constructor(private eleRef: ElementRef) { };
    ngOnInit() {
    };
    handleClick(n: number) {
        if (n < 3) {
            console.log(n);
        } else {
            let smallBox = this.eleRef.nativeElement.querySelector('#box' + n - 1);
            /*this didn't work*/
            smallBox.dispatchEvent('click');
        }

    };
};

#2

Linter instantly pointed the error:

let smallBox = this.eleRef.nativeElement.querySelector('#box' + (n - 1));  // parens

Also you have a typo in ngOnInit


#3

It didn’t work. This is pseudo code. I typed this code here. But in my code editor the code is correct.


#4

I think it’s better to just post a link to the github repo, so everybody can avoid unnecessary typo fixes.

Try this:

smallBox.dispatchEvent(new Event('click'));

#5

Tried that it also didn’t work as well. I don’t have any repo for this code.


#6

Oops sorry. This worked. Thanks a lot.