Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

directive click outside angular 6

I upgraded my Angular from 4 to 6, and consequently had a problem with my click-off policy, 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 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>
like image 280
André Montório Avatar asked May 25 '18 14:05

André Montório


People also ask

How do you find a click outside an element in angular 6?

To go on detection for click outside the component, @HostListener decorator is used in angular. It is a decorator that declares a DOM event to listen for and provides a link with a handler method to run whenever that event occurs.

What are the directives in angular?

Directives are classes that add additional behavior to elements in your Angular applications. Use Angular's built-in directives to manage forms, lists, styles, and what users see.


1 Answers

view:

<div #insideElement></div>

component:

export class SomeClass {
  @ViewChild("insideElement") insideElement;
  @HostListener('document:click', ['$event.target'])

  public onClick(targetElement) {
    const clickedInside = this.insideElement.nativeElement.contains(targetElement);
    if (!clickedInside) {
      console.log('outside clicked');
    }
  }
}
like image 146
YoungHyeong Ryu Avatar answered Sep 25 '22 12:09

YoungHyeong Ryu