Categories
Angular

How to Use Angular Material to Build an Appealing UI

Spread the love

Material Design is a design language developed and released by Google in 2014. It dictates a set of rules that all apps using Material Design must follow. Since Google also develops the Angular framework, Material Design support within the Angular framework is first-class.

If you are familiar with Angular, getting started with Angular Material is easy and the documentation is very good. In this piece, I will walk you through the steps required to get started with Angular Material.


Installing the Framework

To get started, you need the latest version of Node.js and Angular CLI. You can install Node.js by following the instructions here.

Angular CLI can be installed by running npm i -g@angular/cli.

Once installed, run npm install --save @angular/material @angular/cdk @angular/animations to install Angular Material with the Angular Animations library, which is necessary for the Angular Material’s widget’s animations.


Create Your Angular Application

To create a new Angular app, run ng new yourAppName, where yourAppName can be replaced with your preferred name for your app.

When running ng new, use the scss option so that you can use CSS and SCSS code for styling. Also, make sure to select yes if it asks you if you want to include a routing module.

If you want to include the Roboto font and Material icons, add:

<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Type caption for embed (optional)

to index.html to use them globally.

In this example, I will create an app with a login form, forms for updating user info and passwords, and a table for displaying personal information.

First, we have to add the dependencies to app.module.ts , like so:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {
  MatButtonModule,
  MatCheckboxModule,
  MatInputModule,
  MatMenuModule,
  MatSidenavModule,
  MatToolbarModule,
  MatTableModule,
  MatDialogModule,
  MAT_DIALOG_DEFAULT_OPTIONS,
  MatDatepickerModule,
  MatSelectModule,
  MatCardModule
} from '@angular/material';
import { MatFormFieldModule } from '@angular/material/form-field';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { FormsModule } from '@angular/forms';
import { TopBarComponent } from './top-bar/top-bar.component';
import { HomePageComponent } from './home-page/home-page.component';
import { LoginPageComponent } from './login-page/login-page.component';
import { SignUpPageComponent } from './sign-up-page/sign-up-page.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
  declarations: [
    AppComponent,
    TopBarComponent,
    HomePageComponent,
    LoginPageComponent,
    SignUpPageComponent,
    PasswordResetRequestPageComponent,
    PasswordResetPageComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatButtonModule,
    MatCheckboxModule,
    MatFormFieldModule,
    MatInputModule,
    MatMenuModule,
    MatSidenavModule,
    MatToolbarModule,
    MatTableModule,
    FormsModule,
    MatSelectModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Type caption for embed (optional)

The code above incorporates the Angular Material dependencies into our main app module, which is necessary for them to be recognized by Angular when the custom elements are used in the templates.

In style.scss , add @import "~@angular/material/prebuilt-themes/indigo-pink.css"; to import the Angular Material styling.

In addition, you can add:

body {
  font-family: "Roboto", sans-serif;
  margin: 0;
}
form {
  mat-form-field {
    width: 95vw;
    margin: 0 auto;
  }
}
.center {
  text-align: center;
}

into styles.css to use the Roboto font and make the form fit the width of your screen.


Building the UI

Create the skeleton code for the login page by running ng g component loginPage. It will be calledlogin-page.component. The template will be called login-page.component.html and the component is called login-page.component.ts.

In login-page.component.ts add:

<div class="center">
  <h1>Log In</h1>
</div>
<form #loginForm='ngForm'>
  <mat-form-field>
    <input matInput placeholder="Username" required #userName='ngModel' name='userName' [(ngModel)]='loginData.userName'>
    <mat-error *ngIf="userName.invalid && (userName.dirty || userName.touched)">
      <div *ngIf="userName.errors.required">Username is required.
      </div>
    </mat-error>
 </mat-form-field>
  <br>
  <mat-form-field>
    <input matInput placeholder="Password" type='password' required #password='ngModel' name='password' [(ngModel)]='loginData.password'>
    <mat-error *ngIf="password.invalid && (password.dirty || password.touched)">
    <div *ngIf="password.errors.required">Password is required</div
    </mat-error>
  </mat-form-field>
  <br>
  <button mat-raised-button type='submit'>Log In</button>
  <a mat-raised-button>Reset Password</a>
</form>

Type caption for embed (optional)

This creates a form with Angular Material styled inputs, along with Material styled form validation messages.

Now, create a new component by running ng g component settingsPage. This will create a file called settings-page.component.html where you can add the following:

<table mat-table [dataSource]="elements" class="mat-elevation-z8" *ngIf="elements.length > 0">
  <ng-container matColumnDef="key">
    <th mat-header-cell *matHeaderCellDef>
      <h3>Account Data</h3>
    </th>
    <td mat-cell *matCellDef="let element">
      {{element.key | capitalize}}
    </td>
  </ng-container>
  <ng-container matColumnDef="value">
    <th mat-header-cell *matHeaderCellDef></th>
    <td mat-cell *matCellDef="let element">
     {{element.value}}
    </td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

Type caption for embed (optional)

In settings-page.component.ts, add:

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-settings-page',
  templateUrl: './settings-page.component.html',
  styleUrls: ['./settings-page.component.scss']
})
export class SettingsPageComponent implements OnInit {
  elements = [
    {key: 'name', value: 'John Au-Yeung'},
    {key: 'screen name', value: 'AuMayeung'},
  ];
  displayedColumns: string[] = ['key', 'value'];
}

This will display a table on the page. displayedColumns are the columns of the table. Angular Material will loop through the entries in the [dataSource] attribute and display them.

In app-routing.module.ts, add the following:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginPageComponent } from './login-page/login-page.component';
import { SettingsPageComponent } from './settings-page/settings-page.component';
const routes: Routes = [
  { path: 'login', component: LoginPageComponent },
  { path: 'settings', component: SettingsPageComponent },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

This will allow you to access the pages you created by entering the URLs.


Conclusion

Once completed, we end up with the login and settings pages.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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