網站搜尋

javascript - 如何在 Angular2/Angular4 中對通過 querySelector 獲取的原生元素的子元素觸發點擊事件


我嘗試了下面的程式碼,但沒有成功。我使用的是 Angular4。我想要在 handle click 的輸入不小於 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');
        }

    };
};

答案#1

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