Angular2 How to trigger (click) event without clicking

放肆的年华 提交于 2019-12-18 11:43:18

问题


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?


回答1:


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



回答2:


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



回答3:


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

Hope so this can help you ..

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;

}


来源:https://stackoverflow.com/questions/45027331/angular2-how-to-trigger-click-event-without-clicking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!