Angular2 Como disparar un evento (click) sin hacer click

Quiero pasar datos de HTML al componente por lo que he creado un evento como este:

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

Y en el componente:

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

Si hago clic en el evento, veo que todo funciona bien. Pero quiero desencadenar este evento de clic de forma automática ya que quiero que el componente para utilizar 'this.charge' valor de inmediato una vez que el componente se hace la carga.

¿Hay alguna manera de activar el evento (click) automáticamente?

Solución

Dale una referencia ViewChild:

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

En su componente:

@ViewChild('myDiv') myDiv: ElementRef;

triggerFalseClick() {
    let el: HTMLElement = this.myDiv.nativeElement;
    el.click();
}
Comentarios (12)

Puedes activar el evento click en ngOnInit() así: `

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

En el archivo component.ts

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);
  }
}
Comentarios (0)
<div #tutor id="tutor-price" (click)="passCharge(tutor.value['charge'])"><span id="month">월 8회</span> <span id="price"> {{tutor.value['charge']}} </span></div>

Espero que esto te pueda ayudar ..

import { Component, OnInit } from '@angular/core';
tutor:any;
@Component({
      //your component decorater tags
})
export class MyComponent implements OnInit{
   ngOnInit(){
      this.charge = this.tutor.value['charge'];
   }
   passCharge(charge){
   this.charge = charge;

}
Comentarios (0)