我正在尝试以编程方式触发文档单击。
我的测试组件显示在页面中的多个位置,当单击测试组件或触发文档单击时,我希望将它们全部隐藏。
@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方法中以编程方式触发文档单击。有办法做到这一点吗?非常感谢!
发布于 2017-08-04 02:55:53
可以使用HTMLElement.click()在任何元素上触发click事件
document.getElementById('myEl').click() // or the hacky id reference `myEl.click()`您不能单击文档,因为它不是呈现的元素。但是你可以点击整个身体:
document.body.click()https://stackoverflow.com/questions/45492358
复制相似问题