Click Outside Angular 6

Asked

Viewed 1,028 times

0

I upgraded my Angular from 4 to 6, and consequently had a problem with my Outside click directive, it stopped working on all components.

my directive:

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.html Component 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>
  • Are you returning an error ? In order to help you you will have to provide a [mcve] to test the code.

1 answer

-1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.