How to trigger the click event manually?

I am trying to program a document click.

My test-comp shows up in several places on the page and I want to hide all of them when the test click is clicked or the document is clicked.

@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'm not sure how to start the document by clicking programmatically inside my method toggleComponent

. Is there a way to do this? Many thanks!

+3


source to share


1 answer


You can trigger an event click

on any element using HTMLElement.click () :

document.getElementById('myEl').click()

      



You cannot click on the document as it is not a render item. But you can click all over the body:

document.body.click()

      

+5


source







All Articles