如何手动触发点击事件?

时间:2017-08-03 18:52:58

标签: javascript angular dom-events

我正在尝试以编程方式触发文档。

我的test-comp显示在页面的多个位置,我想在单击test-comp或触发文档点击时将它们全部隐藏起来。

@Component({
  selector: 'test-comp',
  template: `<div *ngIf="showMe">stuff</div> and more…`
})

export class TestComponent {
  showMenu: boolean;

  constructor(public elementRef: ElementRef) {
  }

  @HostListener('document:click', ['$event'])
  documentClick(event: MouseEvent) {
    //hide my component when there is a document click    
     this.toggleComponent();
  }

  toggleComponent() {
    // I am trying to programmatically fire a document click here to hide all test-comp if the test-comp   
    // component itself is clicked
    // this.elementRef.nativeElement will select all test-comp component but not sure what to do next
    this.showMe = !this.showMe;
  }

我不确定如何在我的toggleComponent方法中以编程方式单击文档。有办法吗?非常感谢!

1 个答案:

答案 0 :(得分:6)

您可以使用HTMLElement.click()

在任何元素上触发click事件
document.getElementById('myEl').click() # or the hacky id reference `myEl.click()`

您无法点击文档,因为它不是呈现的元素。但你可以点击整个身体:

document.body.click()