Click outside Angular 6

0

I updated my Angle from 4 to 6, and consequently I had a problem with my click outside policy, it stopped working on all the components.

My policy:

import { Directive, Output, EventEmitter, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[clickOutside]'
})
export class ClickOutsideDirective {

  constructor(private _elementRef : ElementRef) { }

  @Output()
  public clickOutside = new EventEmitter();

  @HostListener('document:click', ['$event.target'])
  public onClick(targetElement) {
      const clickedInside = this._elementRef.nativeElement.contains(targetElement);
      if (!clickedInside) {
          this.clickOutside.emit(null);
      }
  }
}

My component.html that makes use of this directive:

<div id="sidenav" *ngIf="this.opened" class="sidenav" [ngClass]="getClasses()" [ngStyle]="getStyles()" clickOutside (clickOutside)="closeOutsideSidenav()">
  <header> {{ navTitle }} </header>
  <i *ngIf="this.showCloseButton" class="iconic iconic-x-thin close-icon" (click)="closeSidenav()"></i>
  <ng-content></ng-content>
</div>
<div *ngIf="this.backdrop && this.opened" class="sidenav-backdrop"></div>
    
asked by anonymous 25.05.2018 / 14:36

1 answer

0
  @HostListener('document:click', ['$event'])
  onClickOutside($event) {
    const clickedInside = this.el.nativeElement.contains($event.target);
    if (!clickedInside) {
      //...
    }
  }
    
08.12.2018 / 00:27
___