How to Build Menu Apps in Angular using Material-UI framework

Angular is an extremely powerful framework for building robust, lightning-fast, responsive applications.

When stepping into the Angular world for the first time, I discovered that even though I had previous experience with HTML, CSS, JS, and more, there is quite a steep learning curve associated with Angular.

That being said, I wanted to make this introductory tutorial to support anyone wanting to get started with Angular because I believe it is an incredible tool to have in any developer’s repertoire!

So, to anyone just beginning with Angular, I hope this is helpful to you.

This tutorial will walk you through, step-by-step, how to create a menu using the Material-UI framework, and use it to navigate through two different components, using routing.

Assuming you have Angular installed on your machine, let’s begin by creating a new project using:

ng new menu-demo

To enable routing in the project, proceed with the “y” option when you see the prompt below:

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

Note: Routing can be enabled after the project is created through generating the routing module, but this way is much simpler as everything is automatically configured for you (you’ll thank me later!).

As a really nice complement to the Angular framework, Google created the Angular Material-UI framework.

This allows the developer to easily implement a simplistic and interactive UI, making it that much easier to make your application that much more appealing.

To integrate Angular Material into your project, navigate to your project directory, and import the framework with:

ng add @angular/material

This command will automatically include all of the required dependencies your projects needs to use to Angular Material, so in other words, out of sight, out of mind!

Once the Angular Material packages are successfully installed, it will prompt you to pick either a pre-built or custom theme to integrate into your project.

This is totally up to you as it will just dictate the color scheme that your application will follow (my favorite is the purple/green theme, but hey, that’s just me).

Additionally, if you don’t like the theme you chose, you can change it at any time! Next, you will want to answer yes to the following prompts:

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

“HammerJS” is used to support gesturing (zoom, rotation, swiping, etc.), while “browser animations for Angular Material” gives you the ability to simply integrate animations into your application (animating button states, smoothing over the transition from routed components, etc.).

Neither of these installations is required, but beware, if you don’t install “browser animations for Angular Material”, you will disable a significant amount of animations used by Angular Material and that would be sad, but the choice is ultimately yours.

Now we can actually start using Angular Material by generating a pre-defined menu (which includes a toolbar and a side navigation menu) through the Angular CLI:

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

This command will generate a new menu component by accessing the Angular Material package. It is required that we give the component a name (I named mine nav-menu).

Once you run this command, the component will be generated, and you will be left with a folder titled nav-menu which contains all the files associated with the new menu component.

The generated nav-menu.component.html file should look something 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>

Once you confirm that your menu component was successfully created, create two more components. We’ll use these components to test our application by switching between them, while keeping the menu on the page the entire time:

ng generate component first-page

ng generate component second-page

This will create two more folders, with the necessary files for each component in each of the folders.

If we open the first-page.component.htmland second-page.component.htmlfiles in the first-page and second-page folders respectively, you should see:

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

And:

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

We are now ready to route the components! We begin by opening the app-routing.module.tsfile, which should contain something similar to:

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 first-page and second-page components we created (Note: We do not import the nav-menu component because we will never be switching between it and another component — it will always remain present on the page).

Next, we are going to add paths to the routes array which will provide a path to the first and second path respectively. Your final app-routing.module.ts file should look like the following:

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 { }

Note: The second path in the routes array is there so that when there is a blank path in the URL, it is redirected to the first-page component, meaning that upon loading, this, along with the menu, will be the default loaded component.

Almost done! Now, we need to go back to the nav-menu.component.html file and make some minor adjustments to it. Since we are only dealing with two components, feel free to remove the third anchor (``) element.

Within the remaining two anchor elements, we need to specify routerLink elements for each, which essentially 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).

Additionally, directly below the commented line saying “Add Content Here”, we need to add the router-outlet directive, which will be filled with different content, based on the current state of the router (i.e. if we are currently routed to the first-page component, that is the component content that will be loaded onto the screen).

The final version of this file should look something like:

<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 finish off our application, we navigate to the app.component.htmlfile, and we replace its contents with:

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

Remember how I said we didn’t need to include the menu component in our routing because it will always be on screen?

This is done by including the app-nav-menu component in the app.component.html file, as we are defining the menu component to be constant throughout the entire application.

Last but not least, let’s take a look at what we’ve created!

We can run the command:

ng serve --open

This will serve our application locally (defaulted to port 4200), with the — open flag automatically opening the browser and displaying the contents of the port.

Voila! Upon loading, we will see:

Page view from first-page component

If we click the Second Page button in the menu, the second-page component will be loaded in, removing the content from the first-page component. We will see:

Page view from second-page component

We are done! Now comes the fun part of building the body of the application, adding more components, services, and learning more about the power and versatility of Angular!

I hope you found this tutorial helpful! Please share if you liked it!

#Angular #CSS #Typescript #Development #Programming

How to Build Menu Apps in Angular using Material-UI framework
2 Likes16.50 GEEK