Skip to main content

Angular Material Introduction

What is Angular Material?

Angular Material is the official UI component library for Angular applications that implements Google's Material Design specifications. It provides a set of high-quality, responsive, and accessible UI components that can be easily integrated into your Angular applications to create modern and consistent user interfaces.

Material Design is a design language developed by Google that combines the classic principles of successful design with innovation and technology. It aims to develop a single underlying system that unifies the user experience across platforms, devices, and input methods.

Why Use Angular Material?

  • Consistent Design: Pre-built components following Material Design guidelines
  • Accessibility: Built-in accessibility features
  • Responsive Components: Works across various screen sizes
  • Theming Support: Customizable themes and color palettes
  • Active Development: Maintained by the Angular team
  • Well Documented: Comprehensive documentation and examples

Getting Started with Angular Material

Installation

To add Angular Material to your Angular project, run the following command in your terminal:

bash
ng add @angular/material

When you run this command, the Angular CLI will:

  1. Install required npm packages
  2. Update your Angular project to use Material Design
  3. Add the necessary module imports
  4. Set up theming
  5. Add typography styles
  6. Add browser animation dependencies

The CLI will ask you several questions:

  • Choose a prebuilt theme or set up a custom one
  • Whether to set up global typography styles
  • Whether to set up browser animations

Setting Up Angular Material

After installation, you'll need to import the specific modules for the components you want to use. Let's walk through a simple example of adding a Material button to your application.

  1. First, create or open your Angular module file (e.g., app.module.ts):
typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonModule } from '@angular/material/button';

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

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatButtonModule // Import the button module
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
  1. Now, you can use Material buttons in your component template (e.g., app.component.html):
html
<h1>Angular Material Demo</h1>
<button mat-button color="primary">Primary Button</button>
<button mat-raised-button color="accent">Accent Button</button>
<button mat-stroked-button color="warn">Warn Button</button>
<button mat-flat-button disabled>Disabled Button</button>
<button mat-fab><mat-icon>add</mat-icon></button>
<button mat-mini-fab><mat-icon>favorite</mat-icon></button>

The output would be a set of styled buttons following Material Design guidelines:

  • A flat primary colored button
  • A raised button with accent color
  • A stroked button with warning color
  • A disabled flat button
  • A floating action button with an add icon
  • A mini floating action button with a heart icon

Core Concepts of Angular Material

1. Material Modules

Angular Material is organized into multiple modules, each responsible for a specific component or feature. This modular approach allows you to import only what you need, reducing bundle size.

For example, if you need buttons and form fields, you would import:

typescript
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';

@NgModule({
imports: [
MatButtonModule,
MatFormFieldModule,
MatInputModule
]
})

2. Theming

Angular Material comes with pre-built themes, but also allows for custom theming using Sass. A theme consists of:

  • Primary palette: The color displayed most frequently across your app's screens and components
  • Accent palette: The color used for the floating action button and interactive elements
  • Warn palette: The color used to convey error states
  • Foreground/background palette: The color used for text and backgrounds

Here's how to create a custom theme:

  1. Create a custom-theme.scss file:
scss
@use '@angular/material' as mat;

// Define custom palettes
$my-primary: mat.define-palette(mat.$indigo-palette, 500);
$my-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);
$my-warn: mat.define-palette(mat.$red-palette);

// Create the theme
$my-theme: mat.define-light-theme((
color: (
primary: $my-primary,
accent: $my-accent,
warn: $my-warn,
),
typography: mat.define-typography-config(),
density: 0,
));

// Apply the theme
@include mat.all-component-themes($my-theme);
  1. Include this file in your angular.json file:
json
"styles": [
"src/custom-theme.scss",
"src/styles.css"
]

3. Typography

Angular Material provides typography utilities that help maintain consistent text styles throughout your application. The typography system is based on the Material Design spec.

You can include Material typography in your application by adding the following to your global styles:

scss
@use '@angular/material' as mat;

// Include the common styles for Angular Material
@include mat.core();

// Define a custom typography config
$custom-typography: mat.define-typography-config(
$font-family: 'Roboto, "Helvetica Neue", sans-serif',
$headline-1: mat.define-typography-level(96px, 96px, 300),
$headline-2: mat.define-typography-level(60px, 60px, 300),
$headline-3: mat.define-typography-level(48px, 48px, 400),
$headline-4: mat.define-typography-level(34px, 40px, 400),
$headline-5: mat.define-typography-level(24px, 32px, 400),
$headline-6: mat.define-typography-level(20px, 32px, 500),
$body-1: mat.define-typography-level(16px, 24px, 400),
$body-2: mat.define-typography-level(14px, 20px, 400),
);

// Apply typography to your Angular Material components
@include mat.all-component-typographies($custom-typography);

Practical Example: Building a Login Form

Let's create a simple login form using Angular Material components:

  1. Import the required modules in your app.module.ts:
typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCardModule } from '@angular/material/card';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';

import { AppComponent } from './app.component';
import { LoginFormComponent } from './login-form/login-form.component';

@NgModule({
declarations: [
AppComponent,
LoginFormComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
MatCardModule,
MatInputModule,
MatFormFieldModule,
MatButtonModule,
MatIconModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
  1. Create the login form component:
typescript
// login-form.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css']
})
export class LoginFormComponent {
loginForm: FormGroup;
hidePassword = true;

constructor(private fb: FormBuilder) {
this.loginForm = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}

onSubmit() {
if (this.loginForm.valid) {
console.log('Form submitted:', this.loginForm.value);
// Add authentication logic here
}
}

getEmailErrorMessage() {
if (this.loginForm.controls['email'].hasError('required')) {
return 'You must enter an email';
}

return this.loginForm.controls['email'].hasError('email') ? 'Not a valid email' : '';
}

getPasswordErrorMessage() {
if (this.loginForm.controls['password'].hasError('required')) {
return 'Password is required';
}

return this.loginForm.controls['password'].hasError('minlength') ?
'Password must be at least 6 characters' : '';
}
}
  1. Create the template for the login form:
html
<!-- login-form.component.html -->
<mat-card class="login-card">
<mat-card-header>
<mat-card-title>Login</mat-card-title>
</mat-card-header>

<mat-card-content>
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<mat-form-field appearance="outline" class="full-width">
<mat-label>Email</mat-label>
<input matInput formControlName="email" placeholder="Ex. [email protected]" required>
<mat-error *ngIf="loginForm.controls['email'].invalid">{{getEmailErrorMessage()}}</mat-error>
</mat-form-field>

<mat-form-field appearance="outline" class="full-width">
<mat-label>Password</mat-label>
<input matInput [type]="hidePassword ? 'password' : 'text'" formControlName="password" required>
<button mat-icon-button matSuffix (click)="hidePassword = !hidePassword" type="button">
<mat-icon>{{hidePassword ? 'visibility_off' : 'visibility'}}</mat-icon>
</button>
<mat-error *ngIf="loginForm.controls['password'].invalid">{{getPasswordErrorMessage()}}</mat-error>
</mat-form-field>

<button mat-raised-button color="primary" type="submit" [disabled]="loginForm.invalid" class="full-width">
Login
</button>
</form>
</mat-card-content>
</mat-card>
  1. Add some styles:
css
/* login-form.component.css */
.login-card {
max-width: 400px;
margin: 2rem auto;
}

.full-width {
width: 100%;
margin-bottom: 15px;
}

mat-card-header {
margin-bottom: 20px;
}

This example demonstrates how to use several Angular Material components together:

  • MatCard for the container
  • MatFormField and MatInput for form inputs
  • MatButton for the submit button
  • MatIcon for the password visibility toggle
  • Form validation with error messages

Common Angular Material Components

Here's a quick overview of some frequently used Angular Material components:

Layout Components

  • mat-card: Container for grouping related content
  • mat-tabs: Organize content into tabbed views
  • mat-expansion-panel: Expandable detail summary
  • mat-grid-list: Grid-based layout system
  • mat-toolbar: Header or footer for your application
  • mat-sidenav: Side navigation container
  • mat-menu: Pop-up menu
  • mat-paginator: Controls for paging through content

Form Controls

  • mat-form-field: Wrapper for form fields
  • mat-input: Text input field
  • mat-select: Dropdown selection component
  • mat-checkbox: Checkbox component
  • mat-radio-button: Radio button component
  • mat-datepicker: Date selection component
  • mat-slider: Range input component

Data Table

  • mat-table: Powerful data table with sorting and filtering
  • mat-sort: Add sorting behavior to tables
  • mat-paginator: Pagination for data tables

Buttons and Indicators

  • mat-button: Various button styles
  • mat-icon: Material icons
  • mat-progress-bar: Linear progress indicator
  • mat-progress-spinner: Circular progress indicator
  • mat-badge: Badge content

Popups and Modals

  • mat-dialog: Modal dialogs
  • mat-snack-bar: Brief messages
  • mat-tooltip: Information on hover

Best Practices

  1. Import only what you need: Import specific Material modules rather than importing everything to reduce bundle size.

  2. Use Angular Material's built-in theming: Leverage the theming system to maintain consistency throughout your application.

  3. Follow accessibility guidelines: Angular Material has built-in accessibility features, but you should still test your application for accessibility.

  4. Responsive design: Use Angular Material's responsive utilities and test your application on different screen sizes.

  5. Custom components: When extending Angular Material components, follow the Material Design guidelines to maintain consistency.

  6. Forms integration: Use Angular's Reactive Forms with Material form components for robust form handling.

Summary

Angular Material provides a comprehensive set of UI components that follow Material Design guidelines. It helps developers create attractive, consistent, and accessible user interfaces for their Angular applications with minimal effort.

Key takeaways from this introduction:

  • Angular Material is the official component library for Angular
  • Installation is simple using the Angular CLI
  • Components are organized into modules that you can import as needed
  • The theming system allows for customization while maintaining design consistency
  • Angular Material components work well with Angular's form handling
  • Built-in accessibility features make your applications more inclusive

Additional Resources

Exercises

  1. Create a simple Angular application with a responsive navigation bar using mat-toolbar and mat-sidenav.

  2. Build a user registration form using Angular Material form components with validation.

  3. Create a dashboard layout using mat-card, mat-grid-list, and other layout components.

  4. Implement a data table with sorting, filtering, and pagination using mat-table and related components.

  5. Create a custom theme for your Angular Material application that matches your brand colors.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)