cyberangles guide

Using Angular Material Design to Beautify Your App

In today’s digital landscape, a polished user interface (UI) is no longer a luxury—it’s a necessity. Users expect apps that are not only functional but also visually appealing, intuitive, and consistent across devices. Enter **Angular Material Design**—a powerful UI component library built specifically for Angular applications. By leveraging Google’s Material Design principles, Angular Material provides pre-built, customizable components that help developers create stunning, responsive, and accessible apps with minimal effort. Whether you’re building a simple dashboard or a complex enterprise application, Angular Material streamlines the UI development process, allowing you to focus on core functionality while ensuring your app looks professional. In this blog, we’ll dive deep into Angular Material: from setup and core components to theming, accessibility, and advanced customization. By the end, you’ll have the tools to transform your Angular app into a visually impressive, user-friendly experience.

Table of Contents

  1. Introduction
  2. What is Angular Material Design?
  3. Getting Started with Angular Material
  4. Core Angular Material Components
  5. Theming Your App with Angular Material
  6. Accessibility Features
  7. Best Practices for Using Angular Material
  8. Advanced Customization
  9. Conclusion
  10. References

What is Angular Material Design?

Angular Material Design is an official UI component library for Angular, developed by the Angular team at Google. It is built on top of Material Design, Google’s design system for creating cohesive, user-centric digital experiences.

Key Features of Angular Material:

  • Pre-built Components: Over 30+ ready-to-use components (buttons, cards, modals, tables, etc.) that follow Material Design guidelines.
  • Theming: Customizable color palettes, typography, and spacing to match your brand.
  • Accessibility: Built-in support for WCAG standards, including ARIA labels, keyboard navigation, and screen reader compatibility.
  • Responsiveness: Components are designed to work seamlessly across mobile, tablet, and desktop.
  • Integration with Angular: Optimized for Angular’s ecosystem, including support for reactive forms, RxJS, and Angular CDK (Component Dev Kit).

Getting Started with Angular Material

Before diving into components, let’s set up Angular Material in a new or existing Angular project.

Prerequisites:

  • Node.js (v14+ recommended)
  • Angular CLI (v12+ recommended). Install it via npm install -g @angular/cli.

Step 1: Create a New Angular Project (Optional)

If you don’t have an existing project, create one using the Angular CLI:

ng new my-material-app  
cd my-material-app  

Step 2: Install Angular Material

Use the Angular CLI’s ng add command to install Angular Material. This command automatically configures dependencies, styles, and theme settings:

ng add @angular/material  

During installation, you’ll be prompted to:

  • Choose a prebuilt theme (e.g., Indigo/Pink, Deep Purple/Amber).
  • Set up typography (recommended: use Angular Material’s typography).
  • Enable animation (recommended: yes, for smooth component transitions).

Step 3: Import Angular Material Modules

Angular Material components are organized into feature modules. To use a component, import its module into your Angular module (e.g., app.module.ts).

For example, to use buttons:

// app.module.ts  
import { NgModule } from '@angular/core';  
import { BrowserModule } from '@angular/platform-browser';  
import { MatButtonModule } from '@angular/material/button'; // Import the button module  

import { AppComponent } from './app.component';  

@NgModule({  
  declarations: [AppComponent],  
  imports: [BrowserModule, MatButtonModule], // Add MatButtonModule here  
  providers: [],  
  bootstrap: [AppComponent]  
})  
export class AppModule {}  

Step 4: Verify Installation

Add a Material button to your app.component.html to test:

<!-- app.component.html -->  
<button mat-raised-button color="primary">Hello Material!</button>  

Run the app with ng serve --open. You should see a blue raised button labeled “Hello Material!”.

Core Angular Material Components

Let’s explore some of the most commonly used Angular Material components and how to implement them.

Buttons & Indicators

Angular Material offers several button variants to match different use cases:

VariantPurpose
mat-buttonFlat button (no elevation)
mat-raised-buttonButton with shadow (elevated)
mat-stroked-buttonOutlined button
mat-icon-buttonIcon-only button
mat-fab/mat-mini-fabCircular floating action button (FAB)

Example: Buttons with Icons

<!-- app.component.html -->  
<button mat-raised-button color="primary">  
  <mat-icon>favorite</mat-icon> Like  
</button>  

<button mat-stroked-button color="accent">  
  <mat-icon>share</mat-icon> Share  
</button>  

<button mat-icon-button color="warn">  
  <mat-icon>delete</mat-icon>  
</button>  

Note: To use mat-icon, import MatIconModule in your module and include the Material Icons font in index.html:

<!-- index.html -->  
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">  

Cards & Containers

Cards are ideal for displaying content in a structured, visually appealing way (e.g., blog posts, product listings).

Example: Basic Card

<!-- app.component.html -->  
<mat-card>  
  <mat-card-header>  
    <mat-card-title>Welcome to My App</mat-card-title>  
    <mat-card-subtitle>Your journey starts here</mat-card-subtitle>  
  </mat-card-header>  
  <mat-card-content>  
    <p>Angular Material makes UI design simple and consistent. Explore components to build beautiful apps!</p>  
  </mat-card-content>  
  <mat-card-actions>  
    <button mat-button>Learn More</button>  
    <button mat-button>Subscribe</button>  
  </mat-card-actions>  
</mat-card>  

Import MatCardModule in your module to use cards.

Angular Material provides navigation tools like toolbars, sidebars, and tabs to help users navigate your app.

Example: Toolbar with Sidebar Toggle

<!-- app.component.html -->  
<mat-toolbar color="primary">  
  <button mat-icon-button (click)="toggleSidebar()">  
    <mat-icon>menu</mat-icon>  
  </button>  
  <span>My Material App</span>  
  <span class="spacer"></span>  
  <button mat-button>Login</button>  
</mat-toolbar>  

<mat-sidenav-container>  
  <mat-sidenav #sidenav mode="side" opened="false">  
    <mat-nav-list>  
      <a mat-list-item routerLink="/home">Home</a>  
      <a mat-list-item routerLink="/about">About</a>  
      <a mat-list-item routerLink="/contact">Contact</a>  
    </mat-nav-list>  
  </mat-sidenav>  
  <mat-sidenav-content>  
    <!-- Main content goes here -->  
  </mat-sidenav-content>  
</mat-sidenav-container>  

Import MatToolbarModule, MatSidenavModule, and MatListModule in your module. Add CSS for spacing:

/* styles.scss */  
.spacer {  
  flex: 1 1 auto;  
}  

Forms & Inputs

Angular Material simplifies form creation with styled inputs, selectors, checkboxes, and date pickers.

Example: Reactive Form with Material Inputs

<!-- app.component.html -->  
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">  
  <mat-form-field appearance="fill">  
    <mat-label>Name</mat-label>  
    <input matInput formControlName="name" required>  
    <mat-error *ngIf="userForm.get('name')?.invalid">Name is required</mat-error>  
  </mat-form-field>  

  <mat-form-field appearance="outline">  
    <mat-label>Email</mat-label>  
    <input matInput type="email" formControlName="email" required>  
    <mat-error *ngIf="userForm.get('email')?.hasError('email')">Invalid email</mat-error>  
  </mat-form-field>  

  <mat-form-field appearance="fill">  
    <mat-label>Favorite Color</mat-label>  
    <mat-select formControlName="color">  
      <mat-option value="red">Red</mat-option>  
      <mat-option value="blue">Blue</mat-option>  
      <mat-option value="green">Green</mat-option>  
    </mat-select>  
  </mat-form-field>  

  <button mat-raised-button color="primary" type="submit">Submit</button>  
</form>  

In your component class (app.component.ts):

import { Component } from '@angular/core';  
import { FormBuilder, FormGroup, Validators } from '@angular/forms';  

@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.scss']  
})  
export class AppComponent {  
  userForm: FormGroup;  

  constructor(private fb: FormBuilder) {  
    this.userForm = this.fb.group({  
      name: ['', Validators.required],  
      email: ['', [Validators.required, Validators.email]],  
      color: ['']  
    });  
  }  

  onSubmit() {  
    if (this.userForm.valid) {  
      console.log('Form submitted:', this.userForm.value);  
    }  
  }  
}  

Import MatFormFieldModule, MatInputModule, MatSelectModule, and ReactiveFormsModule in your module.

Data Tables

Material tables are powerful for displaying tabular data with sorting, pagination, and filtering.

Example: Basic Data Table

<!-- app.component.html -->  
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">  
  <!-- Name Column -->  
  <ng-container matColumnDef="name">  
    <th mat-header-cell *matHeaderCellDef> Name </th>  
    <td mat-cell *matCellDef="let user"> {{user.name}} </td>  
  </ng-container>  

  <!-- Email Column -->  
  <ng-container matColumnDef="email">  
    <th mat-header-cell *matHeaderCellDef> Email </th>  
    <td mat-cell *matCellDef="let user"> {{user.email}} </td>  
  </ng-container>  

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>  
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>  
</table>  

In your component class:

import { Component } from '@angular/core';  

@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.scss']  
})  
export class AppComponent {  
  displayedColumns: string[] = ['name', 'email'];  
  dataSource = [  
    { name: 'John Doe', email: '[email protected]' },  
    { name: 'Jane Smith', email: '[email protected]' }  
  ];  
}  

Import MatTableModule in your module. For advanced features like sorting/pagination, import MatSortModule and MatPaginatorModule.

Theming Your App with Angular Material

One of Angular Material’s most powerful features is its theming system, which lets you customize colors, typography, and spacing to align with your brand.

Custom Themes

A theme in Angular Material is defined by three color palettes:

  • Primary: Dominant color for key elements (buttons, toolbars).
  • Accent: Secondary color for highlights (links, icons).
  • Warn: Error/alert color (delete buttons, validation errors).

Step 1: Define a Custom Theme
Create a _theme.scss file in src/theme/ (or directly in src/styles.scss):

// src/theme/_theme.scss  
@import '~@angular/material/theming';  

// Define custom palettes  
$my-primary: mat-palette($mat-indigo); // Use Material's indigo palette  
$my-accent: mat-palette($mat-pink, A200, A100, A400); // Custom accent shades  
$my-warn: mat-palette($mat-red);  

// Create light and dark themes  
$my-light-theme: mat-light-theme((  
  color: (  
    primary: $my-primary,  
    accent: $my-accent,  
    warn: $my-warn,  
  )  
));  

$my-dark-theme: mat-dark-theme((  
  color: (  
    primary: $my-primary,  
    accent: $my-accent,  
    warn: $my-warn,  
  )  
));  

// Include the theme styles  
@include angular-material-theme($my-light-theme);  

Step 2: Apply the Theme
Import the theme file in styles.scss:

// src/styles.scss  
@import './theme/_theme';  

Dark Mode Support

To toggle between light and dark themes, use a class-based approach.

Example: Theme Toggle Button

<!-- app.component.html -->  
<button mat-button (click)="toggleTheme()">  
  <mat-icon>{{isDarkTheme ? 'brightness_7' : 'brightness_4'}}</mat-icon>  
  {{isDarkTheme ? 'Light Mode' : 'Dark Mode'}}  
</button>  

In _theme.scss, add a dark theme mixin under a class:

// src/theme/_theme.scss  
.dark-theme {  
  @include angular-material-theme($my-dark-theme);  
}  

In your component:

// app.component.ts  
isDarkTheme = false;  

toggleTheme() {  
  this.isDarkTheme = !this.isDarkTheme;  
  document.body.classList.toggle('dark-theme', this.isDarkTheme);  
}  

Accessibility Features

Angular Material prioritizes accessibility (a11y) out of the box. Here are key features:

  • ARIA Labels: Components automatically generate ARIA attributes (e.g., mat-button adds role="button").
  • Keyboard Navigation: All interactive components (buttons, modals, tabs) support keyboard input (e.g., Tab for focus, Enter to activate).
  • Focus Management: Modals and dialogs trap focus for screen readers.
  • High Contrast: Themes include high-contrast modes for readability.

Best Practice: Enhance Accessibility
Add custom ARIA labels to improve clarity:

<button mat-icon-button aria-label="Delete item">  
  <mat-icon>delete</mat-icon>  
</button>  

Best Practices for Using Angular Material

  1. Keep It Consistent: Stick to Material Design guidelines for spacing, typography, and color to avoid confusing users.
  2. Optimize Performance: Lazy-load Material modules using Angular’s loadChildren to reduce initial bundle size.
  3. Use Typography: Leverage Angular Material’s typography system (mat-typography mixin) for consistent text styles.
  4. Test Responsiveness: Use Angular Material’s built-in breakpoints (via @angular/cdk/layout) to ensure components work on all screen sizes.
  5. Avoid Over-Customization: Overriding core component styles can break accessibility and updates. Use themes instead.

Advanced Customization

Custom Component Styles with Mixins

Angular Material provides Sass mixins to customize component styles without breaking the theme.

Example: Custom Button Styles

// src/theme/_theme.scss  
@import '~@angular/material/theming';  

// Custom button style  
.my-custom-button {  
  @include mat-button-base; // Inherit base button styles  
  background-color: #ff5722;  
  color: white;  
  border-radius: 8px;  

  &:hover {  
    background-color: #e64a19;  
  }  
}  

Integrate with Flex Layout

For advanced responsive design, use @angular/flex-layout (a popular library for building flexible layouts with Material Design).

Example: Flex Layout with Cards

<div fxLayout="row" fxLayout.xs="column" fxLayoutGap="16px">  
  <mat-card fxFlex="33%">Card 1</mat-card>  
  <mat-card fxFlex="33%">Card 2</mat-card>  
  <mat-card fxFlex="33%">Card 3</mat-card>  
</div>  

Conclusion

Angular Material Design is a game-changer for Angular developers, offering a robust set of components, theming tools, and accessibility features to build beautiful, functional apps. By following Material Design guidelines and leveraging Angular Material’s flexibility, you can create UIs that delight users and align with modern design standards.

Whether you’re a beginner or an experienced developer, Angular Material simplifies UI development, letting you focus on what matters most: building great user experiences.

References