0

I was using the below link to create a sidebar using angular animation and it works perfectly well. https://stackblitz.com/edit/angular-sidebar-animation?file=src%2Findex.html

But I want to add functionality to close the sidebar when user click outside the sidebar.

Deepak
  • 93
  • 1
  • 8
  • I think this may help you https://stackblitz.com/edit/ng-sidenav-experiments?file=src%2Fapp%2Fapp.component.html – Tzimpo Feb 27 '20 at 09:49
  • I ended up doing something like that but for the whole screen Thanks everyone – Deepak Feb 29 '20 at 11:04

3 Answers3

0

Genrally, side-bar or Drawer be used as a panel typically overlaid on top of a page and slides in from the side. User can interact with the side-bar or drawer without leaving the current page.

In your case though it is working almost, still there are few more things required. See below 'ant' angular component for such functionality which solves all of your issues and it is open-source.

Ant Drawer: https://ng.ant.design/components/drawer/en

RGR
  • 1,471
  • 2
  • 22
  • 35
0

You can refer to the following post for getting solution in jquery how-do-i-detect-a-click-outside-an-element

if you dont want to use jquery, based on the above post you can modify your code a little bit.

app.component.html

<button (click)="toggleMenu($event)" class="hamburger">
 <span>toggle menu</span>
</button>
<h1>{{name}} Sidebar</h1>

<app-menu [@slideInOut]="menuState" ></app-menu>

AppComponent Class of app.component.ts file

export class AppComponent {
 name = "Angular";
 ngOnInit() {
  window.addEventListener("click", () => {
  this.menuState = this.menuState === 'in' ? 'out' : 'out';
 });
}
menuState: string = "out";

toggleMenu(event) {
 event.stopPropagation();
 this.menuState = this.menuState === 'out' ? 'in' : 'out';
}
}

This should do the trick.

Milan Lakhani
  • 275
  • 2
  • 11
0

Please take a look at this stackblitz I added a directive ClickOutsideDirective that checks if clik is in or out menu

import {Directive, ElementRef, Output, EventEmitter, 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);
        }
    }
}
BELLIL
  • 653
  • 10
  • 20