How to trigger click event manually?

巧了我就是萌 提交于 2020-08-02 07:24:32

问题


I am trying to trigger a document click programatically.

My test-comp are shown in multiple places in a page and I want to hide them all when the test-comp is clicked or a document click is fired.

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

I am not sure how to fire a document click programmatically inside my toggleComponent method. Is there a way to do it? Thanks a lot!


回答1:


You can trigger a click event on any element by using HTMLElement.click():

document.getElementById('myEl').click() # or the hacky id reference `myEl.click()`

You can't click on document since it is not a rendered element. But you can click on the whole body:

document.body.click()


来源:https://stackoverflow.com/questions/45492358/how-to-trigger-click-event-manually

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