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

Lea*_*Lea 25 data-binding mouseclick-event typescript angular

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

<div id="tutor-price" (click)="passCharge(r.value['charge'])"><span id="month">? 8?</span> <span id="price"> {{r.value['charge']}} </span></div>
Run Code Online (Sandbox Code Playgroud)

在组件中,

passCharge(charge){
   this.charge = charge;
   console.log(this.charge,"give me the number")
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 46

给它一个ViewChild参考:

<div #myDiv id="tutor-price" (click)="passCharge(r.value['charge'])"><span id="month">? 8?</span> <span id="price"> {{r.value['charge']}} </span></div>
Run Code Online (Sandbox Code Playgroud)

在您的组件中:

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

triggerFalseClick() {
    let el: HTMLElement = this.myDiv.nativeElement;
    el.click();
}
Run Code Online (Sandbox Code Playgroud)

  • @Xan 因为我解释了,而不是给出最快的解决方案。 (2认同)

Gau*_*shn 8

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

<div #divClick id="tutor-price" (click)="passCharge(r.value['charge'])">
    <span id="month">? 8?</span> 
    <span id="price"> {{r.value['charge']}} </span>
</div>`
Run Code Online (Sandbox Code Playgroud)

在 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);
  }
}
Run Code Online (Sandbox Code Playgroud)


che*_*zeh 5

扩展接受的答案,如果您收到错误“无法读取未定义的属性'nativeElement'”甚至“无法读取未定义的属性单击”,正如OP在提供的答案的注释中明确指出的那样,请使用以下解决方案

如果您想获取托管组件或指令的元素的引用,您需要指定您需要该元素而不是组件或指令

@ViewChild('myDiv', { read: ElementRef }) myDiv: ElementRef<HTMLElement>;
Run Code Online (Sandbox Code Playgroud)