Angular nativeElement contains() not working as expected for document:click

Viewed 2010

I've got code to detect if somewhere outside a component is being clicked, problem is that one of the elements dropdown-items inside my component is being detected as a click outside the component. Could be to do with the ngIf..

if (!this.el.nativeElement.contains(event.target))

some of the template:

  <div class="dropdown-items" *ngIf="showList">
    <div *ngFor="let item of dropdownItems" (click)="onClickItem(item)" class="dropdown-item">
      {{item.name}}
    </div>
  </div>

So when the dropdown list is expanded, then items clicked from the list the toggleShowList is called when it shouldn't be.

  @HostListener('document:click', ['$event'])
  documentClick(event: MouseEvent) {
    if (!this.el.nativeElement.contains(event.target)) {
      this.toggleShowList();
      console.log('clicked window outside button');
    }
  }
0 Answers
Related