Angular2 How to trigger (click) event without clicking
You can trigger click event in ngOnInit() like this: `
<div #divClick id="tutor-price" (click)="passCharge(r.value['charge'])">
<span id="month">월 8회</span>
<span id="price"> {{r.value['charge']}} </span>
</div>`
In component.ts file
import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
@Component({
//component decoraters
})
export class MyComponent implements OnInit, AfterViewInit {
@ViewChild('divClick') divClick: ElementRef;
ngOnInit() {
// your other code
setTimeout(() => {
this.divClick.nativeElement.click();
}, 200);
}
}
Expanding on the accepted answer, if you get the error "Cannot read property 'nativeElement' of undefined" or even "Cannot read property click of undefined", as OP clearly states in the comments to answer provided, use this solution:
If you want to get a reference of an element that hosts a component or directive you need to specify that you want the element instead of the component or directive
@ViewChild('myDiv', { read: ElementRef }) myDiv: ElementRef<HTMLElement>;
Give it a ViewChild reference :
<div #myDiv id="tutor-price" (click)="passCharge(r.value['charge'])"><span id="month">월 8회</span> <span id="price"> {{r.value['charge']}} </span></div>
In your component :
@ViewChild('myDiv') myDiv: ElementRef<HTMLElement>;
triggerFalseClick() {
let el: HTMLElement = this.myDiv.nativeElement;
el.click();
}