Angular / Bootstrap: collapse nav togglemenu when clicking outside

Viewed 652

I am new to Angular and I try to close my navigation toggle menu when I click outside of the dropdown. I try to do this with the ng-click-outside directive, but for some reason it does not work. At the moment it does not do anything at all or it toggles in when I click outside (what i don't want). On click outside it should be closed if it is toggled in at the moment. The onClickedOutside() method already counts the amount of clicks outside the right way. What I have so far:

nav.component.html:

    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
      <a class="navbar-brand" routerLink="/landing">MYSITE</a>
      <button class="navbar-toggler"
          type="button"
          data-toggle="collapse"
          data-target="#navbarText"
          aria-controls="navbarText"
          aria-expanded="false"
          aria-label="Toggle navigation"
          [attr.aria-expanded]="!collapsed"
          (click)="collapsed = !collapsed"
          (clickOutside)="collapsed == false ? collapsed = true : collapsed = false"> // this does not work as expected
     <span class="navbar-toggler-icon"></span>
     </button>

    <div class="collapse navbar-collapse" id="navbarText" [class.collapse]="collapsed">
      <ul class="navbar-nav mr-auto mt-2 mt-lg-0  mx-md-auto order-1 order-md-2">
        <li class="nav-item active" ngbDropdown [routerLinkActive]="['active']">
          <a class="nav-link" routerLink="/landing">Landing Page</a>
        </li>
     </ul>
    </div>
   </nav>

navbar.component.ts

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-navbar',
      templateUrl: './navbar.component.html',
      styleUrls: ['./navbar.component.scss']
    })
    export class NavbarComponent implements OnInit {
      collapsed = true;
      constructor(public breakpointObserver: BreakpointObserver) {}

      onClickedOutside(e: Event) {
        if (!this.collapsed) {
          console.log('Clicked outside:');
        }
      }
     }
0 Answers
Related