Karellism

4. Creating Side Navigation

May 4th, 2019
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!

To create side navigation items, we are going to use the mat-nav-list element that resides inside MatListModule. So, let’s register this module first in the material.module.ts file:

import { … MatListModule } from '@angular/material';

imports: [
MatListModule,

exports: [
MatListModule,

Then let’s create the sidenav-list component and modify the sidenav-list.component.html file:

ng g component navigation/sidenav-list --spec false

<mat-nav-list>
<a mat-list-item routerLink="/home" (click)="onSidenavClose()">
<mat-icon>home</mat-icon> <span class="nav-caption">Home</span>
</a>
<a mat-list-item routerLink="/owner" (click)="onSidenavClose()">
<mat-icon>assignment_ind</mat-icon> <span class="nav-caption">Owner Actions</span>
</a>
<a mat-list-item routerLink="#" (click)="onSidenavClose()">
<mat-icon>account_balance</mat-icon><span class="nav-caption">Account Actions</span>
</a>
</mat-nav-list>

we use the mat-nav-list as a container with all the anchor tags containing the mat-list-item attributes. The click event is there for every link, to close the side-nav as soon as a user clicks on it. Finally, every link contains its own mat-icon.

Let’s continue by adding some styles to the sidenav-list.component.css file:

a {
text-decoration: none;
color: white;
}

a:hover, a:active{
color: lightgray;
}

.nav-caption{
display: inline-block;
padding-left: 6px;
}

And finally let’s modify the sidenav-list.component.ts file:

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

@Component({
selector: 'app-sidenav-list',
templateUrl: './sidenav-list.component.html',
styleUrls: ['./sidenav-list.component.css']
})
export class SidenavListComponent implements OnInit {
@Output() sidenavClose = new EventEmitter();

constructor() { }

ngOnInit() {
}

public onSidenavClose = () => {
this.sidenavClose.emit();
}

}

That’s it. We can now open the app.component.html file and modify it to add the side-nav component:

<mat-sidenav #sidenav role="navigation">
<app-sidenav-list (sidenavClose)="sidenav.close()"></app-sidenav-list>
</mat-sidenav>

In this code, we react on the event emitter from the sidenav-list component and close the side-nav by using the #sidenav local reference.

Add Comment
Please, Sign In to add comment