Create an Application-Wide Menu in Angular Using Material UI

Angular is a very strong framework for creating robust, quick, and responsive apps.

When I initially entered the Angular universe, I learned that, despite my past familiarity with HTML, CSS, JS, and other technologies, there is a high learning curve connected with Angular.

That being stated, I decided to create this basic video to assist anyone interested in getting started with Angular because I feel it is a fantastic tool to have in any developer’s arsenal!

So, if you’re just getting started with Angular, I hope this is useful.

This article will show you how to design a menu with the Material-UI framework and use it to move between two separate components using routing.

Assuming you have Angular installed, let’s get started by making a new project with:

ng new menu-demo

When you get the prompt below, choose “y” to allow routing in the project:

? Would you like to add Angular routing? (y/N)

Note: Routing may be enabled after the project is established by producing the routing module, but this method is much simpler because everything is configured for you (you’ll thank me later!).

Google built the Angular Material-UI framework as an excellent complement to the Angular framework.

This enables the developer to simply design a simple and engaging user interface, making it much easier to make your program more appealing.

To incorporate Angular Material into your project, go to the project directory and import the framework using:

ng add @angular/material

This script will automatically include all of the dependencies your project requires to use Angular Material, so out of sight, out of mind!

After successfully installing the Angular Material packages, you will be prompted to select either a pre-built or custom theme to incorporate into your project.

This is entirely up to you because it will simply decide the color scheme that your application will use (my personal preference is the purple/green theme, but that’s just me).

Furthermore, if you do not like the theme you selected, you may change it at any moment! Next, you should say yes to the following questions:

? Set up HammerJS for gesture recognition? Yes
? Set up browser animations for Angular Material? Yes

“HammerJS” is used to enable gestures (zooming, rotating, swiping, and so on), whereas “browser animations for Angular Material” allows you to easily add animations into your application (animating button states, smoothing over the transition from routed components, etc.).

Neither of these installs is essential, however, be aware that if you do not install “browser animations for Angular Material,” you would deactivate a considerable number of Angular Material animations, which would be unfortunate, but the option is ultimately yours.

We can now begin utilizing Angular Material by producing a pre-defined menu (with a toolbar and a side navigation menu) using the Angular CLI:

ng generate @angular/material:material-nav --name="nav-menu"

By using the Angular Material package, this command will create a new menu component. It is necessary that we name the component (I named mine nav-menu).

When you run this command, the component will be produced, and you will be left with the nav-menu folder, which has all of the files connected with the new menu component.

The resulting nav-menu.component.html file should look like this:

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav #drawer class="sidenav" fixedInViewport
      [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
      [mode]="(isHandset$ | async) ? 'over' : 'side'" 
      [opened]="(isHandset$ | async) === false">
    <mat-toolbar>Menu</mat-toolbar>
    <mat-nav-list>
      <a mat-list-item href="#">Link 1</a>
      <a mat-list-item href="#">Link 2</a>
      <a mat-list-item href="#">Link 3</a>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <mat-toolbar color="primary">
      <button
        type="button"
        aria-label="Toggle sidenav"
        mat-icon-button
        (click)="drawer.toggle()"
        *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      <span>menu-demo</span>
    </mat-toolbar>
    <!-- Add Content Here -->
  </mat-sidenav-content>
</mat-sidenav-container>

Create two more components after you’ve confirmed that your menu component was correctly built. We’ll put our application to the test by switching between these components while keeping the menu on the page:

ng generate component first-page

ng generate component second-page

This will generate two new directories, one for each component, with the relevant files in each folder.

When we open the files first-page.component.html and second-page.component.html in the first-page and second-page directories, we should see:

<p>first-page works!</p>
<p>second-page works!</p>

The components are now ready to be routed! To begin, open the app-routing.module.ts file, which should look something like this:

import { NgModule } from ‘@angular/core’;
import { Routes, RouterModule } from ‘@angular/router’;

const routes: Routes = [];
@NgModule({
   imports: [RouterModule.forRoot(routes)],
   exports: [RouterModule]
})
export class AppRoutingModule { }

We now want to import the components we developed for the first and second pages (Note: We do not import the nav-menu component since we will never move between it and another component — it will always be present on the page).

Next, we’ll add pathways to the routes array, which will offer a path to the first and second paths. The finished app-routing.module.ts file should look like this:

import { NgModule } from ‘@angular/core’;
import { Routes, RouterModule } from ‘@angular/router’;
import { FirstPageComponent } from ‘./first-page/first-page.component’;
import { SecondPageComponent } from ‘./second-page/second
page.component’;

const routes: Routes = [
{ path: ‘first-page’, component: FirstPageComponent },
{ path: ‘’, redirectTo: ‘/first-page’, pathMatch: ‘full’ },
{ path: ‘second-page’, component: SecondPageComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

The second path in the routes array is there so that if the URL has a blank path, it is forwarded to the first-page component, which means that this, along with the menu, will be the default loaded component when the page loads.

Almost finished! Now we must return to the nav-menu.component.html file and make some minor changes. Feel free to omit the third anchor () element as we are just working with two components.

We need to supply routerLink elements for each of the remaining two anchor elements, which effectively tell Angular how to respond when you click on the link (in our case, the response is to switch between the first-page and second-page components).

In addition, right after the commented line that says “Add Information Here,” we need to add the router-outlet directive, which will be populated with various content depending on the router’s current state (i.e. if we are currently routed to the first-page component, that is the component content that will be loaded onto the screen).

This file’s final version should look like this:

<mat-sidenav-container class=”sidenav-container”>
  <mat-sidenav #drawer class=”sidenav” fixedInViewport
      [attr.role]=”(isHandset$ | async) ? ‘dialog’ : ‘navigation’”
      [mode]=”(isHandset$ | async) ? ‘over’ : ‘side’”
      [opened]=”(isHandset$ | async) === false”>
    <mat-toolbar>Menu</mat-toolbar>
    <mat-nav-list>
      <a mat-list-item routerLink=”/first-page”>First Page</a>
      <a mat-list-item routerLink=”/second-page”>Second Page</a>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <mat-toolbar color=”primary”>
      <button
        type=”button”
        aria-label=”Toggle sidenav”
        mat-icon-button
        (click)=”drawer.toggle()”
        *ngIf=”isHandset$ | async”>
        <mat-icon aria-label=”Side nav toggle icon”>menu</mat-icon>
      </button>
      <span>menu-demo</span>
    </mat-toolbar>
    <! — Add Content Here →
    <router-outlet></router-outlet>
  </mat-sidenav-content>
</mat-sidenav-container>

Finally, to complete our application, we go to the app.component.html file and change the contents with:

<app-nav-menu></app-nav-menu>
<router-outlet></router-outlet>

Remember how I mentioned we didn’t need to include the menu component in our routing because it would be visible at all times?

This is accomplished by adding the app-nav-menu component in the app.component.html file, as the menu component is defined to be consistent throughout the application.

Finally, let’s have a look at what we’ve made!

We can use the following command:

ng serve --open

This will serve our application locally, with the — open flag opening the browser and displaying the contents of the port.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories