Angular2如何在不点击的情况下触发(点击)事件

Angular2 How to trigger (click) event without clicking

我想将数据从 HTML 传递到组件,所以我创建了一个这样的事件:

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

并且在组件中:

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

如果我单击该事件,我会发现一切正常。 但是我想自动触发这个点击事件,因为我希望组件在加载完成后立即使用 'this.charge' 值。

有什么方法可以自动触发(点击)事件吗?

给它一个 ViewChild 引用:

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

在你的组件中:

@ViewChild('myDiv') myDiv: ElementRef<HTMLElement>;

triggerFalseClick() {
    let el: HTMLElement = this.myDiv.nativeElement;
    el.click();
}
<div #tutor id="tutor-price" (click)="passCharge(tutor.value['charge'])"><span id="month">월 8회</span> <span id="price"> {{tutor.value['charge']}} </span></div>

希望对你有帮助..

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;

}

您可以像这样在 ngOnInit() 中触发点击事件: `

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

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

, 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 上扩展:

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