简体   繁体   中英

Angular 6 - click outside menu

I'm creating a click event to document that close my aside menu, I created example in jquery but i don't want to do this in jquery and I cannot access to 'menu' variable.

How can I write this in pure angular ?

import { Component, HostListener, ElementRef } from "@angular/core";
import { Router } from "../../node_modules/@angular/router";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  menu: boolean;
  date = new Date();

  @HostListener('document:click', ['$event'])
  clickout(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      this.menu = false;
    } else {
      console.log('clicked outside');
    }
  }

  constructor(public router: Router,
              private eRef: ElementRef) {}

  showMenu() {
    this.menu = !this.menu;
  }


}

EDIT I edited code from duplicate, but I have different idea

Is there other HostListener to ignore aside and button with id ? Or am I thinking wrong ?

When i click on aside or button menu this clickout event must not working, when i click anywhere else it should set me this.menu to false.

<aside id="aside" [hidden]="!menu">
  <button class="menu-btn" (click)="menu = false" routerLink="/">Strona Główna</button>
  <button (click)="menu = false" routerLink="/cv">CV</button>
  <button (click)="menu = false" routerLink="/bio">BIO</button>
  <button (click)="menu = false" routerLink="/portfolio">Portfolio</button>
  <button (click)="menu = false" routerLink="/kontakt">Kontakt</button>
</aside>
<button id="menu-btn" [class.aside]="menu" (click)="showMenu()">Klik</button>

As suggested in this answer , you can detect the document click events with HostListener . To make sure that mouse clicks don't reach the document when the menu is clicked, you should stop the propagation of the event in the click event handler set on the aside element:

<aside [hidden]="!menu" (click)="handleAsideClick($event)">
@HostListener('document:click', ['$event']) clickout(event) {
  // Click outside of the menu was detected
  ...
}

handleAsideClick(event: Event) {
  event.stopPropagation(); // Stop the propagation to prevent reaching document
  ...
}

如果您只想在菜单外单击,您可以通过以下方式以编程方式触发对文档正文的单击:

document.body.click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM