Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 : close menu when click outside

I would like to know whenever click is triggered inside parent div #menu, irrelavant of html tags exists inside it.

nativeElement.parent didn't worked for me.

HTML code:

<button #toggleButton (click)="toggleMenu()"> Toggle Menu</button>

 <div class="menu" *ngIf="isMenuOpen" #menu>
    <div>
      I'm the menu. Click outside to close me
    </div>
    </div>

Angular script:

this.renderer.listen('window', 'click',(e:Event)=>{

        if(e.target !== this.toggleButton.nativeElement && e.target!==this.menu.nativeElement){
            this.isMenuOpen=false;
        }
    });

This is not working.

like image 506
Lavanya Avatar asked Dec 07 '22 12:12

Lavanya


1 Answers

Add Host to component meta tag.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  host: {
    "(window:click)": "onClick()"
  }
})

stopPropagation()

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.

toggleMenu($event) {    
    $event.stopPropagation();
    this.isMenuOpen = !this.isMenuOpen;
  }

  onClick() {
    this.isMenuOpen = false;
  }

Example:https://stackblitz.com/edit/angular-oenkbw

like image 65
Chellappan வ Avatar answered Dec 11 '22 10:12

Chellappan வ