Saturday, August 18, 2018

Angular 6 - Material Module Usage

1) @angular/material is one of the new feature in Angular 6.

  • Add "@angular/material": "^6.3.0", in package.json and run npm install
  • after npm install run ng add @angular/material
  • generates Navigation component using 
    • ng generate @angular/material:material-nav
  • Add below import to app.component.ts 

import { BreakpointObserver, Breakpoints, BreakpointState } from '@angular/cdk/layout';
import { Observable } from 'rxjs';

  • Add below variable after an existing variable in app.component.ts file
isHandset: Observable<BreakpointState> = this.breakpointObserver.observe(Breakpoints.Handset);

  • Add the constructor after that variable.
constructor(private breakpointObserver: BreakpointObserver) {}

  • open and edit `src/app/app.component.html` then replace all HTML tags with this tags.

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav
    #drawer
    class="sidenav"
    fixedInViewport="true"
    [attr.role]="isHandset ? 'dialog' : 'navigation'"
    [mode]="(isHandset | async)!.matches ? 'over' : 'side'"
    [opened]="!(isHandset | async)!.matches">
    <mat-toolbar color="primary">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)!.matches">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      <span>Application Title</span>
    </mat-toolbar>
  </mat-sidenav-content>
</mat-sidenav-container>
Next, give it a style by open and edit `src/app/app.component.css` then add this lines of CSS syntax.
.sidenav-container {
  height: 100%;
}

.sidenav {
  width: 200px;
  box-shadow: 3px 0 6px rgba(0,0,0,.24);
}

No comments: