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

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';

    selector: 'box-frame',
    template: `
              <div (click)="handleClick(i)" id="box{{i}}" *ngFor="let i of array"></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) {
        } else {
            let smallBox = this.eleRef.nativeElement.querySelector('#box' + n - 1);
            /*this didn't work*/


Linter instantly pointed the error:

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

Also you have a typo in ngOnInit

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

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'));
1 Like

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

Oops sorry. This worked. Thanks a lot.

A post was split to a new topic: Angular - How to trigger a div located in other commponent and triggering from another component?