Angular - Automatically hide sidebar menu upon selecting a menu item

Struggling to hide a sidebar menu after clicking on a menu item that you created? I ran into the same issue and tried following the example from a tutorial on

Do I really need to call toggleMenu on (click) of every hyperlink in the HTML? If so, how do I invoke a method that resides in app.component.ts from another component?

Help needed...

Currently, I'm working with Angular 4 and bootstrap 4.

Check out the relevant code snippets below:

<button (click)="toggleMenu()" class="hamburger">
  <span>toggle menu</span>
</button>

<navigation-component [@slideInOut]="menuState"> </navigation-component>

<div class="container-fluid">
  <alert></alert>
  <router-outlet></router-outlet>
</div>

app.component.ts:

@Component({
  selector: 'app-root',
  templateUrl: './'  + (window.innerWidth > 745 ? 
          'app.component.html' :
          'app.component.mobile.html'),
  styleUrls: ['./app.component.css'],
  animations: [
               trigger('slideInOut', [
                 state('in', style({
                   transform: 'translate3d(0, 0, 0)'
                 })),
                 state('out', style({
                   transform: 'translate3d(100%, 0, 0)'
                 })),
                 transition('in => out', animate('400ms ease-in-out')),
                 transition('out => in', animate('400ms ease-in-out'))
               ]),
             ]
})
  toggleMenu() {
      // Toggle the menu state
      this.menuState = this.menuState === 'out' ? 'in' : 'out';
  }

Need more guidance? Check out the links below for further reference:

https://stackblitz.com/edit/dynamic-nested-sidenav-menu

Here's the updated code snippet for navigation.component.ts:

toggleMenu() {
    this.toggleMenu();
}

Stay on track with this solution:

After incorporating the code suggested by Santosh in app.component.ts, everything worked smoothly. Big thanks to Santosh!

  constructor(private http: Http,
          private router: Router,
          public zone: NgZone) {
          router.events.subscribe( (event: Event) => {
              if (event instanceof NavigationStart) {
                  this.menuState = 'out';
              }

              if (event instanceof NavigationEnd) {
                  // Hide loading indicator
              }

              if (event instanceof NavigationError) {
                  // Hide loading indicator
                  // Present error to user
                  console.log(event.error);
              }
          });
  }

Answer №1

To manage this, you can utilize router events and update the value of this.menuState to 'out' whenever a route changes.

For a useful code example, you can refer to this link

Answer №2

To implement toggling functionality in NgZone, you need to include a specific module.

import { NgZone } from '@angular/core';

Next, within the constructor, create a zone variable.

constructor(public zone: NgZone){}

Finally, define your toggle logic inside the Zone() method as shown below:

toggleMenu() {
    this.zone.run(()=>{
    this.menuState = this.menuState === 'out' ? 'in' : 'out';
   })
}

Answer №4

Optimizing router navigation by only running solutions when needed can greatly improve performance. With this approach, the code will only execute when necessary, such as when a route change occurs due to a link click or function call.

An example of this approach can be seen here, where the click event is listened to and state is changed accordingly.

Answer №5

Below is the revised answer with a link to toggle the navigation bar when clicking on the submenu.

Updated Answer

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with situations where an Angular component's route lacks a resolver

I have a component that handles both creating new items and updating existing ones. I have set up a Resolver for the 'edit/:id' route, but have not used one for the 'new' route. ngOnInit() { if (!(this.route.snapshot.url[0].path ...

What is the reason behind Typescript executing the abstract class before anything else?

I'm currently facing a challenge solving an abstract class problem with Typescript. Let me explain what I am trying to accomplish. There is a class named Sword that extends Weapon. Each Weapon must have certain properties like the damage, but since e ...

Repeatedly invoke http.post function and finally return the observable

In order to attach the list of documents, each document can contain a maximum of 20 MB data and the user has the ability to attach an unlimited number of files. Consequently, I am initiating one file upload per REST call. Upon successfully saving all the ...

What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overl ...

Dynamically altering the CSS4 variables in real time

I am facing the challenge of managing multiple CSS4 variables, including primary, for various companies. How can I dynamically change the primary CSS4 variable color based on the company? Note: My specific requirement is to update the primary variable glo ...

Modifying Angular components does not cause *ngFor to update

Currently facing an issue with my Angular 5 project. I have a parent component that is responsible for displaying child components based on elements in my cartProducts array. Each child component receives a cartProduct object as input. The data for these c ...

Issue in React Native and Firestore: The 'auth' property is not recognized in the specified type or an error object of unknown type

I am currently using Typescript in conjunction with Firebase and React Native. While working on the signup screen, I included Firebase like so: import * as firebase from 'firebase/app'; import 'firebase/auth'; In my onSignUp function, ...

An object may be null when its type is A or undefined, but we are certain it is not undefined

Since the release of version 4.8.4, the TypeScript compiler has been flagging an issue with the following code: type A = {v: number} function get_the_first<T>(xs: T[]): T | undefined { if (xs.length > 1) return xs[0]; else ...

Creating uniform width children with Bootstrap's flexbox

Within my flex box container, the children are all displayed in a flex-row. I'm utilizing bootstrap to try and make sure that all the children have the same width and height. HTML <div class="d-flex flex-row flex-grow"> <div class="backgroun ...

Is there a secure alternative in Typescript for handling null values, such as a "safe operator"?

I'm currently working on implementing a feature in my Angular application where I need to toggle the visibility of a div using ngIf. Below you can find the snippet of HTML code I am using: <div *ngIf="damageReportToPolice()"> </div> Her ...

Tips for providing a base URL in Angular to fetch images from an API

How do I access the API URL to retrieve images from a database? <table class="table"> <tr> <th>Id</th> <th>Image</th> </tr> ...

The NGRX state in Angular is not being properly saved by the local storage

Currently, I am utilizing NGRX for state management within my Angular application. While NGRX is functioning correctly, I have encountered an issue with using local storage to persist the NGRX state. Upon refreshing the browser, the NGRX data reverts back ...

The paginator feature is not supported by mat-table

My mat-table seems to be ignoring the paginator setting: https://i.sstatic.net/HLJrI.png In the screenshot provided, all 7 people are displayed on the first page instead of the expected 5. I have followed various tutorials on implementing paginators, incl ...

Downloading Excel files in Angular using File Saver

Previously, I had set up a PHP post form that would download an excel file upon clicking the button. The form data was also posted to the URL successfully using plain HTML and submit form. This is the function in PHP that gets triggered when the form is p ...

The autocomplete suggestions appear as faded gray text following the cursor in the input field, rather than displaying as a pop-up selection

My website is built using Angular 10 and Angular Material. I am looking to enhance the input suggestions in matInput, but in a unique way that differs from matAutocomplete. Instead of displaying a list of options, I want to show just one suggestion for a ...

Errors in the @babel/types during the ng build process in Angular version 8.2.14

When I execute the command 'ng build' for my Angular App, I encounter the following errors: ERROR in ../node_modules/@types/babel-types/index.d.ts:1769:96 - error TS1144: '{' or ';' expected. 1769 export function assertArrayE ...

Attempting to test a Jasmine directive in Angular results in failure

After creating a simple directive that throws an error when the input is invalid, I encountered an issue with my testing. When attempting to test for the thrown error using expect().toThrow(), it succeeded as expected. However, the same result occurred w ...

The performance of linting has significantly decreased following the upgrade of nx/angular, particularly for the plugin import/no-deprecated

The upgrade process of the project involved moving from version 11.2.11 to version 12.2.10 through the nx upgrade process (nx migrate) Following this upgrade, the code linting process now takes around 4 minutes, compared to the previous 30 seconds: time ...

Click on the photo and drag your mouse outside of it to zoom out [Angular2]

HTML <div class="zoomPhoto" *ngIf="zoomed" (click)="unZoomPhoto()"> <img src="{{currentPhoto}}" [style.margin-left.px]="-(zoomedPhotoWidth/2)" [style.margin-top.px]="-(zoomedPhotoHeight/2)" #photo /> </div> CSS .zoomPhoto{ backg ...

Upgrading Angular from version 5 to 6 resulted in the Angular.json file not being generated

As I follow the official guide to upgrade my Angular app to version 10, I am currently facing an issue while trying to upgrade to CLI version 6 following the instructions on update.angular.io. It is important to ensure that you are using Node 8 or later. ...