Angular2 How to trigger (click) event without clicking

Lea picture Lea · Jul 11, 2017 · Viewed 97.5k times · Source

I want to pass data from HTML to the component so I've created an event like this:

<div id="tutor-price" (click)="passCharge(r.value['charge'])"><span id="month">월 8회</span> <span id="price"> {{r.value['charge']}} </span></div>

And in component:

passCharge(charge){
   this.charge = charge;
   console.log(this.charge,"give me the number")
}

If I click the event, I see everything's working fine. But I want to trigger this click event automatically since I want the component to use 'this.charge' value right away once the component is done the loading.

Is there any way I can trigger (click) event automatically?

Answer

user4676340 picture user4676340 · Jul 11, 2017

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();
}