Create a responsive sidebar menu with Angular Material » Zoaib Khan (2024)

Sidebar navigation menus are the most common layout pattern used by web apps nowadays. But most of the components that we have are not really responsive. In this article I’m going to walk you through creating a truly responsive sidebar navigation menu in Angular using the Angular Material library.

More specifically what I mean by a responsive sidebar is the following.

On desktop or larger screen sizes, we have enough real estate, so we’d like the sidebar to remain visible at all times, reminding the user of the different sections of the site. On smaller screen sizes, we’d like to hide the sidebar and show it only when the user wants to navigate to another section. Here is the final result of our tutorial showing this behavior.

Pretty clean and intuitive, right? Let’s get started to see exactly how to do this!

Video tutorial

Check out the video tutorial below. Or if you’re more of a reader, continue with the text version! 🙂

Setting up our project

Let’s first set up our Angular project by running the following commands on our terminal (with the Angular CLI).

ng new angular-responsive-sidebarng add @angular/material

These commands create an Angular app and add the Angular Material components library to it. Let us now import the modules we require in our app.module.ts file.

@NgModule({ declarations: [AppComponent], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, MatDividerModule, ], providers: [], bootstrap: [AppComponent],})export class AppModule {}

Great, now we can move on to add our components in the template!

Adding our toolbar and sidebar components

Let’s add the material toolbar and the material side navigation bar to our main app.component.html file.

<mat-toolbar>Responsive side navigation</mat-toolbar><mat-sidenav-container> <mat-sidenav> </mat-sidenav> <mat-sidenav-content> <div class="content mat-elevation-z8"> Main content here! </div> </mat-sidenav-content></mat-sidenav-container>

As you can see, the material side navigation component has some parts to it. The container is actually called the mat-sidenav-container. This has the mat-sidenav and the mat-sidenav-content sections inside of it.

mat-sidenav is your sidebar menu while mat-sidenav-content is the main content of your app. You could keep any content here, including a router-outlet. You’ll most probably be using routes to show different sections of the site here. In our case, I’ve just kept some text to show it’s the main content.

Let’s now see how we added some styles to spice up the layout!

Styling our layout to give an elevated look

Here is how our app.component.scss file looks like for now.

mat-toolbar { background: #004a9f; color: white;}mat-sidenav { margin: 16px; width: 200px; border-right: none; background: #002b5c; color: white; border-radius: 10px; padding: 16px; text-align: center;}.content { height: calc(100vh - 98px); border-radius: 10px; margin: 16px; margin-left: 32px; display: flex; justify-content: center; align-items: center; font-size: 2rem; color: lightgray;}mat-sidenav-container { height: calc(100vh - 65px);}

What we’ve done here is add some background and foreground colors to setup our design. Then, we’ve added margins for the sections to appear with some spacing between them. The fixed heights are there so the sections appear completely on the page (any scrolling will be inside of them).

Lastly, we’ve added some tweaks such as a rounded border and some elevation using the mat-elevation-z8 class which comes with material.

<mat-sidenav class="mat-elevation-z8">...</mat-sidenav><mat-sidenav-content> <div class="content mat-elevation-z8"> Main content here! </div></mat-sidenav-content>

As a result, we have our basic layout all set up like below.

Create a responsive sidebar menu with Angular Material » Zoaib Khan (1)

Great! Let’s add some menu items and styling to our sidebar navigation menu now.

Styling our sidebar and adding the menu items

This is strictly not needed for this app, but I wanted to make a more complete example of a sidebar. If you’re more interested in the functionality of the responsive sidebar in Angular, please skip to the next section!

Ok, let’s now add some menu items aka buttons to the sidebar.

<mat-sidenav class="mat-elevation-z8"> <button mat-button class="menu-button"> <mat-icon>home</mat-icon> <span>Home</span> </button> <button mat-button class="menu-button"> <mat-icon>person</mat-icon> <span>Profile</span> </button> <button mat-button class="menu-button"> <mat-icon>info</mat-icon> <span>About</span> </button> <mat-divider></mat-divider> <button mat-button class="menu-button"> <mat-icon>help</mat-icon> <span>Help</span> </button> </mat-sidenav>

This is pretty standard stuff – some material button components with icons related to them. In a real app obviously you’ll also have routerLink on each of them linking to the different routes of your app. Here is how it looks like (with some styling which I’ll show in a bit).

Create a responsive sidebar menu with Angular Material » Zoaib Khan (2)

To make it more real, let’s also add a section at the top of the sidebar with the profile of a user.

<img class="avatar mat-elevation-z8" src="https://source.unsplash.com/c_GmwfHBDzk/200x200" /><h4 class="name">John Smith</h4><p class="designation">Software Engineer</p><mat-divider></mat-divider>

And the styles associated with these elements.

.menu-button { width: 100%; display: flex; align-items: center; justify-content: flex-start; font-size: 1rem; mat-icon { margin-right: 8px; }}.avatar { margin-top: 16px; width: 100px; height: 100px; border-radius: 50%;}.name { margin-top: 8px; font-weight: normal;}.designation { margin-top: 2px; font-size: 0.7rem; color: lightgrey;}mat-divider { margin-top: 16px; margin-bottom: 16px; background-color: rgba(255, 255, 255, 0.5);}

For the most part, the styles have the colors and spacing needed for each of the elements. The avatar also has a border radius to give it the shape of a circle. And that’s pretty much it!

Create a responsive sidebar menu with Angular Material » Zoaib Khan (3)

Nice. This looks much more authentic and can very well be used in a real app. Now that our sidebar looks good, let’s move on to making it responsive!

Check out my related article on creating a responsive card grid in Angular here.

Making the sidebar responsive

To make the sidebar responsive, the material sidenav component provides us with a property called mode. For large screen sizes, we want the mode to be side. This means that the sidenav will always remain visible and our main content displayed with it.

The other mode is over. We’ll need this when we want the sidebar to be hidden normally, but only appear over the content when we want to navigate to some other section.

So all we need is a way to switch between these modes when the screen size changes. Fortunately, we can detect screen size changes with the Angular CDK layout package and its BreakpointObserver service. Let’s see some code!

export class AppComponent { @ViewChild(MatSidenav) sidenav!: MatSidenav; constructor(private observer: BreakpointObserver) {} ngAfterViewInit() { this.observer.observe(['(max-width: 800px)']).subscribe((res) => { if (res.matches) { this.sidenav.mode = 'over'; this.sidenav.close(); } else { this.sidenav.mode = 'side'; this.sidenav.open(); } }); }}

There are a few things going on here. Let’s go through them one by one.

First, we have a ViewChild decorator at the very top to get the MatSidenav component reference in our code. Then, we include the BreakpointObserver service in our constructor.

We’re using the observe method of the BreakpointObserver which can take in any number of breakpoints. If any of them matches or changes state (i.e. stops matching), all subscriptions to the method are notified.

In our case, we’re using 800px as our breakpoint. This means if it matches, we’ve to switch to the over mode for our sidebar and close it. And vice versa, if it doesn’t match.

Remember to keep the subscription in the ngAfterViewInit lifecycle method, so that we’re assured we have the sidenav initialized before calling it!

Great! Now if you reduce and increase your screen width using Developer tools, you’ll be able to see the sidebar appearing and disappearing as we want it.

Adding the sidebar menu toggle button for small screens

But wait, while the sidebar navigation menu hides on smaller screens, we have no way for it to show itself when we need it. We need a menu toggle button allow opening and closing of the menu on smaller screens! Let’s add that now.

<mat-toolbar class="mat-elevation-z8"> <button mat-icon-button *ngIf="sidenav.mode === 'over'" (click)="sidenav.toggle()"> <mat-icon *ngIf="!sidenav.opened"> menu </mat-icon> <mat-icon *ngIf="sidenav.opened"> close </mat-icon> </button> Responsive side navigation</mat-toolbar><mat-sidenav #sidenav="matSidenav" class="mat-elevation-z8">...</mat-sidenav>

The first thing you need to note is at the very bottom. We’ve added a template variable for the sidenav component using the #sidenav="matSidenav" syntax. This is basically doing the same thing as we did with the ViewChild decorator before, but this makes the reference available in the template.

For the toggle button, we’re using a material icon button. We’ve added an *ngIf directive to it so that it only shows when the sidenav has the over mode, which will happen on smaller screens. The button’s click event simply calls the toggle function of the sidenav component.

Lastly, we add some additional *ngIf directives to check whether the sidenav is open or not and show a different icon so it’s visually clear to the user.

And that’s it! Here’s our finished product again. A clean and intuitive responsive sidebar in Angular for you 🔥

Conclusion

With the proliferation of tablets and mobiles nowadays, it is a given that your web app needs to be responsive in its layout. This article provides for one way of making a responsive sidebar in Angular with material components and the CDK package.

If we give some thought to it, this can be combined with other components to make them responsive as well with not much effort – providing an intuitive interface to your users whichever platform they use!

I hope you’ve found this useful in some way. If so, check out my other related articles below and/or follow me on twitter for updates on future articles!

The complete code for this tutorial can be found at this github repository.

Thanks for reading! Bye 😊

Support me!

If you enjoyed this or any of my other posts, you can support me by buying me a coffee below. Thanks in advance!

Read more posts like this:

  1. Create a responsive card grid in Angular using Flex Layout
  2. Create a responsive navbar in Angular using Flex Layout
  3. Angular Material Dark Mode in 3 steps
  4. Design a Weather Card With Angular Material and CSS
Create a responsive sidebar menu with Angular Material » Zoaib Khan (2024)

FAQs

How to create responsive sidebar in Angular? ›

To make the sidebar responsive, the material sidenav component provides us with a property called mode. For large screen sizes, we want the mode to be side. This means that the sidenav will always remain visible and our main content displayed with it. The other mode is over.

How to make form responsive in Angular material? ›

Angular University
  1. use the Angular BreakpointObserver to detect the size of the current device.
  2. set member variables in your component that allow you to show or hide certain elements depending on the screen size.
  3. Set responsive CSS classes in your component like is-phone-portrait depending on the screen size.
Jan 20, 2023

How to create a side bar in Angular? ›

  1. Prerequisites.
  2. Setting up angular project.
  3. Adding Dependencies.
  4. Installing Syncfusion Sidebar Package. Ivy library distribution package. Angular compatibility compiled package(ngcc)
  5. Adding Styles.
  6. Adding Sidebar module.
  7. Adding Syncfusion component.
  8. Run the application.

What is angular simple sidebar menu? ›

Angular Sidebar or Sidenav menu is an expandable and collapsible component that typically acts as a side container to place primary or secondary content alongside the main content. It provides flexible options to be shown and hidden based on user interactions.

Is angular material grid responsive? ›

Definition of Angular Material Responsive Grid. In Angular material, we have a grid layout that is used to create the two-dimensional list view. Also in the material library, we have a grid list module which is useful to create e the grid layout in angular.

How do I create a sticky sidebar menu? ›

You can either make a custom stylesheet specifying the sidebar style or you can add an inline CSS code "position: sticky" to your sidebar element/container.

How do I create a dynamic reactive form? ›

We are going to use the following steps in our existing code.
  1. Import Reactive Forms module in Dynamic Forms project. ...
  2. Import FormGroup and Form Control in app. ...
  3. Create FormGroup in app.component Class. ...
  4. Create a function in app. ...
  5. Dynamic Forms template file changes in app.
Feb 24, 2021

How do you make responsive in React material UI? ›

Responsive layouts in Material Design adapt to any possible screen size. We provide the following helpers to make the UI responsive: Grid: The Material Design responsive layout grid adapts to screen size and orientation, ensuring consistency across layouts. Container: The container centers your content horizontally.

How will you create an editable dynamic table using Angular materials? ›

  1. [Part 1] Create an editable dynamic table. Introduction. Setup an Angular app with Material UI. Create a basic read-only Material table. Create a dynamic table using columns schema. ...
  2. [Part 2] Add and remove table rows.
  3. [Part 3] Load, add, update and delete data using API services.
  4. [Part 4] Validate Table Rows and Fields.
Apr 8, 2022

What is the difference between material drawer and sidenav? ›

The difference between the two components is that the sidenav component should be used for a global drawer (like a navigation drawer) while the drawer component should be used for content specific to the small portion of your app (such as allowing the user to filter files).

What is the difference between sidenav and drawer in angular material? ›

Angular Material provides two sets of components to add collapsible side content. These are sidenav and drawer components. 2. The sidenav components add side content to a full screen app whereas drawer components add side content to a small section of our app.

How do I use Sidenav in Angular materials? ›

To set up a sidenav we use three components: <mat-sidenav-container> which acts as a structural container for our content and sidenav, <mat-sidenav-content> which represents the main content, and <mat-sidenav> which represents the added side content.

How do I edit the sidebar menu? ›

Start by clicking on Appearance » Widgets from your WordPress dashboard. Next, drag the Navigation Menu widget to the sidebar column. Create a title for your new widget and select the menu you want to display from the drop-down menu. Click Save to confirm your changes.

What is the best grid system for responsive design? ›

8px grid definition

A best practice is to build your layout with an 8px Grid, a geometric foundation of all the visual elements that include typography and iconography as well. We'll review this 8px grid later on another article.

How do I make my mat grid responsive? ›

You have to set the cols attribute of the mat-grid-list dynamically depending on the screen width. You'd have to decide on which width breakpoint will the mat-grid-list render the 1-column version.

Is Angular material better than Bootstrap? ›

Angular flex-layout provides a robust grid system that relies on CSS flex. The attractiveness of this layout depends on how you describe the layout areas with each other. Angular Material and flex layout are better than Bootstrap.

How do I make a floating sidebar widget? ›

Enabling your sidebar to float with a visitor is very easy. Go to Appearance and click, “Widgets.” Click on a sidebar widget to expand its settings. At the bottom, you'll see a new option available.

How do I create a sidebar menu in CSS? ›

You can add menu items in that space if you want.
  1. Step 1: Create a basic html structure to create sidebars. ...
  2. Step 2: Design the background using css code. ...
  3. Step 3: Add profile images and titles. ...
  4. Step 4: Add menu items in the sidebar. ...
  5. Step 5: Design menu items with css code. ...
  6. Step 6: Create navigation bar.
Jun 20, 2021

What is a floating sidebar widget? ›

A sticky, floating, or fixed, sidebar widget in WordPress is a widget that's locked into place, so when a user scrolls down the page, it doesn't disappear. In other words, the information found in the sticky sidebar is accessible at any time.

How to create dynamic reactive forms in Angular? ›

Building dynamic forms
  1. Prerequisites.
  2. Enable reactive forms for your project.
  3. Create a form object model.
  4. Define control classes.
  5. Compose form groups.
  6. Compose dynamic form contents.
  7. Supply data.
  8. Create a dynamic form template.

How to generate dynamic form from JSON with Angular? ›

Summary
  1. Set up the JSON data source.
  2. Create a new component.
  3. Pass JSON data into the component.
  4. Creating the Reactive form from the JSON data.
  5. Rendering form inputs dynamically in the template.
Jul 7, 2021

What is reactive forms in Angular? ›

Reactive forms provide access to information about a given control through properties and methods provided with each instance. These properties and methods of the underlying AbstractControl class are used to control form state and determine when to display messages when handling input validation.

How to create a responsive navbar using material UI? ›

Create a Drawer. js file in the component folder and in that file, create a DrawerComponent function. Import Drawer from Material UI, then create a function named DrawerComponent which will return a Drawer and a ListItem and this is where we will place the list of items we want in our responsive navigation bar.

How do you make a React material table responsive? ›

You can achieve equal spacing in-between the columns then you should do this: <Table> uses the table-layout: 'fixed' CSS prop, leading to all columns having the same width, combined with white-space: 'nowrap' on every table cell to handle the overflow.

Is material UI responsive? ›

Material design's responsive UI is based on a 12-column grid layout. This grid creates visual consistency between layouts, while allowing flexibility across a wide variety of designs. The number of grid columns varies based on the breakpoint system.

How to display dynamic data in Angular material table? ›

let's start, Add the <mat-table> component to create a table and provide a data source from where the table can get the data to display. You can provide a data source by using the DataSource property. The next step is to create a template for dynamic columns in your Material table.

How do we create custom pagination in Angular? ›

Create a folder named app-pagination in your app's component folder. We will create all the components and modules in this folder only. Now, we will create the component for pagination. You can create the component by executing the below command in the app-pagination directory created in the first step.

How to show the dynamic table with dropdown in Angular? ›

Create another column in your first table to provide a checkbox for selecting each row or multiple rows and bind the value of checkbox to the id property in your data. Create a button and on click event, call a method to get the ids of the selected rows from the checkbox values.

What are the 3 types of navigation drawers? ›

There are two types of navigation drawers: standard and modal.

What is the size of sidenav in angular material? ›

In angular material, md-sidenav has these attributes: width: 304px; min-width: 304px; That's why the width will be fixed at 304 px no matter what device you use. So if you want to change your sidenav width you'll have to change the css a bit.

How to open and close sidebar in Angular? ›

Opening and closing the Sidebar can be achieved with built-in public methods.
...
Open and close the sidebar in Angular Sidebar component
  1. show() : Method to open the Sidebar.
  2. hide() : Method to close the Sidebar.
  3. toggle() : Method to toggle between open and close states of the Sidebar.

How do I create a custom navigation menu? ›

To do this go to Appearance >Menus and start creating a new menu. Give the menu the title “Secondary Menu”, select “My Custom Menu” for a location and then hit the “Create Menu” button. Finally add some items to the menu (for example Menu item 1, Menu item 2, Menu item 3) and then save the menu.

Does angular material have a navbar? ›

Angular material also provides us navbar, which is nothing but collapsible side content. This type of site content can be used to show the menu of an application or different types of features available to the application.

How to create toolbar in Angular material? ›

Creating toolbars with multiple rows in Angular Material can be done by placing <mat-toolbar-row> elements inside of a <mat-toolbar> . Note: Placing content outside of a <mat-toolbar-row> when multiple rows are specified is not supported.

What is the alternative for Angular material? ›

We have compiled a list of solutions that reviewers voted as the best overall alternatives and competitors to Angular Material, including Syncfusion Essential Studio Enterprise Edition, Progress Kendo UI, DevExpress, and PrimeNG.

Is Angular material and material UI same? ›

For Angular JS developers, Angular Material is a UI component library.

Which component is used to create the side drawer? ›

Adding the Side Drawer

The <SideDrawer> component is a very simply component with just a bunch of lines of JSX code. The most important part here is the SideDrawer. css file which ensures that the drawer looks like a typical drawer and is positioned above the other page content.

How do I toggle Sidenav from another component? ›

Open/Close sidenav from another component
  1. header. component, in which there is a control button for right-sidenav.
  2. rigth-sidenav. component, in which is the right-sidenav.
  3. sidenav. component (this is the left main menu), this component calls header. component, right-sidenav. component and content.

What is the use of @NgModule in Angular? ›

@NgModule takes a metadata object that describes how to compile a component's template and how to create an injector at runtime. It identifies the module's own components, directives, and pipes, making some of them public, through the exports property, so that external components can use them.

How do I import a mat menu? ›

Menu items in Angular
  1. step 1: Import Angular material Menu module. We can import material menu module (MatMenuModule) in our components ts file or app. ...
  2. step 2: Use mat Menu selector to display Menu Items. ...
  3. step 3: Add matMenuTriggerFor Element.

What is a sidebar navigation menu? ›

The sidebar menu is the set of links on the left-hand side of the page. The purpose of the sidebar is to show users the available information within a section of pages and provide a way for them to view it. Sidebar menus can be applied to pages from the back-end editor.

How do I show categories in sidebar? ›

In the WordPress sidebar, hover over Appearance and select Widgets from the pop-out contextual menu. Drag and drop the Categories widget from the list of Available Widgets on the left side of the screen into a location on the right side of the screen, such as Default Sidebar.

What is a sidebar menu? ›

A sidebar enables app navigation and provides quick access to top-level collections of content in your app or game. The term sidebar refers to a list of top-level app areas and collections, almost always displayed in the primary pane of a split view.

How do I add a menu to the sidebar? ›

Navigate to Appearance>Widgets. Find Navigation Menu under Available Widgets, then drag and drop it over to the Sidebar widget area. Add a Title for your navigation menu and select the menu you want to use from the dropdown.

How do I customize my sidebar widget? ›

To create a sidebar with the WordPress Customizer:
  1. From your WordPress dashboard, select Appearance > Customizer.
  2. In the customizer, choose Widgets, then the sidebar you want to edit.
  3. Click Add a Widget and choose a widget from the menu. ...
  4. Customize your widget settings. ...
  5. Add as many widgets to your sidebar as you like.
Dec 16, 2020

How do I change my sidebar widget? ›

To remove a sidebar widget, click on it, and its contents should roll down to show. Click the red “Remove” in the bottom right. To add a new widget, click the “Add a Widget” button in the bottom right. This will show you all the widgets, and you'll select the one you want, and control it the same way.

How do I customize friendly sidebar navigation? ›

Few tips to make the sidebar navigation easy to scan or less frustrating for the users.
  1. Use the logo. ...
  2. Add the relevant icons to the links. ...
  3. Indicate the currently active link. ...
  4. Differentiate group links. ...
  5. Use badges & tooltips to collapsed the sidebar.

How do I make a responsive React page? ›

To use the react-responsive library, we first need to install it using npm. Once the library is installed, we can import it into our React component. This React component uses the useMediaQuery hook to check the screen size and orientation of the user's device.

How do you make a navbar responsive React? ›

Making Navbar Responsive

You can make the Navbar responsive in two ways. The first one uses CSS and another uses React. Using CSS: In CSS, you can simply change the display to none or block at your desired width to just completely change the HTML style. Using React: In React, you can use a useMediaQuery hook.

How do you make a component responsive? ›

To make a component responsive to its container, just wrap it in an element with this attribute, and let your CSS do the rest! Note: if you want to use custom breakpoints on a per-container basis, you can! See the custom breakpoints demo for an example.

What makes a page responsive? ›

Responsive web design, or RWD, is a design approach that addresses the range of devices and device sizes, enabling automatic adaption to the screen, whether the content is viewed on a tablet, phone, television, or watch. Responsive web design isn't a separate technology — it is an approach.

What do we create responsive page in HTML? ›

Responsive web design is used to make your web page look appropriate, good, and well placedon all devices (desktop, tablet, smartphone etc.) Responsive web design uses HTML and CSS to resize, hide, shrink, enlarge, or move the content. It makes the content look good on any screen.

How do you make a navbar responsive in material UI? ›

Create a Drawer. js file in the component folder and in that file, create a DrawerComponent function. Import Drawer from Material UI, then create a function named DrawerComponent which will return a Drawer and a ListItem and this is where we will place the list of items we want in our responsive navigation bar.

How do I make my navbar responsive with Flexbox? ›

The Navigation Bar (Navbar)
  1. Create The HTML. Following the semantic rule, let's create a <header> since our navbar is the header of the page. ...
  2. Prepare The HTML For Styling. ...
  3. Start Styling With CSS. ...
  4. Styling The <body> ...
  5. Styling The Typography. ...
  6. Styling The Layout. ...
  7. Make The Navbar Responsive With Media Queries. ...
  8. Closing.
Jan 28, 2021

How do you make an interactive navbar in React? ›

Building a navbar with Bootstrap
  1. Go to your React application and create a src/Navigation folder.
  2. Create a src/Navigation/Navbar. js file inside the src/Navigation directory.
  3. Create an empty navbar function in your file: import React from "react"; const Navbar = () => { return () } export default Navbar.
Mar 18, 2022

What are the three modes for opening a sidenav? ›

Opening and closing a sidenav

A <mat-sidenav> can be opened or closed using the open() , close() and toggle() methods.

How to create sidebar using JavaScript? ›

Example
  1. height: 100%; /* 100% Full-height */ width: 0; /* 0 width - change this with JavaScript */ position: fixed; /* Stay in place */ ...
  2. padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; ...
  3. position: absolute; top: 0; right: 25px; ...
  4. font-size: 20px; cursor: pointer; background-color: #111;

Top Articles
Latest Posts
Article information

Author: Lidia Grady

Last Updated:

Views: 6249

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lidia Grady

Birthday: 1992-01-22

Address: Suite 493 356 Dale Fall, New Wanda, RI 52485

Phone: +29914464387516

Job: Customer Engineer

Hobby: Cryptography, Writing, Dowsing, Stand-up comedy, Calligraphy, Web surfing, Ghost hunting

Introduction: My name is Lidia Grady, I am a thankful, fine, glamorous, lucky, lively, pleasant, shiny person who loves writing and wants to share my knowledge and understanding with you.