Angular Material: Building Beautiful UIs with Ease

Angular Material is a UI component library for Angular developers that provides a set of well-designed and pre-built UI components to help build beautiful and responsive user interfaces with ease. In this tutorial, we will explore the various components and features of Angular Material and learn how to use them effectively in our Angular applications.

angular material building beautiful uis ease

What is Angular Material?

Angular Material is a UI component library that is built and maintained by the Angular team. It is designed to work seamlessly with Angular, providing a set of reusable and customizable UI components that follow the Material Design guidelines. Material Design is a design language developed by Google, which focuses on simplicity, consistency, and usability.

Benefits of using Angular Material

Using Angular Material in your Angular applications offers several benefits:

  1. Consistent Design: Angular Material follows the Material Design guidelines, providing a consistent and familiar look and feel across different devices and platforms. This ensures that your application's UI will be visually appealing and user-friendly.

  2. Responsive Layout: Angular Material provides a responsive grid system and components that automatically adapt to different screen sizes and orientations. This makes it easier to create responsive and mobile-friendly UIs without writing custom CSS.

  3. Accessibility: Angular Material components are designed with accessibility in mind, making it easier to create accessible applications that can be used by people with disabilities.

  4. Easy Customization: Angular Material provides a theming system that allows you to easily customize the look and feel of your application. You can choose from pre-built themes or create your own custom theme to match your brand or design requirements.

Getting Started

Before we can start using Angular Material, we need to install it and import the necessary modules into our Angular application.

Installation

To install Angular Material, open your terminal and navigate to your Angular project directory. Then, run the following command:

npm install @angular/material @angular/cdk

This will install the required dependencies for Angular Material and the Angular Component Development Kit (CDK).

Importing Angular Material modules

After installing Angular Material, we need to import the necessary modules into our Angular application. Open the app.module.ts file and add the following imports:

import { NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDialogModule } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatMenuModule } from '@angular/material/menu';
import { MatTableModule } from '@angular/material/table';
import { MatToolbarModule } from '@angular/material/toolbar';

@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    // ...
    MatButtonModule,
    MatCardModule,
    MatDialogModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatMenuModule,
    MatTableModule,
    MatToolbarModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In this example, we are importing some common Angular Material modules such as MatButtonModule, MatCardModule, MatDialogModule, and others. These modules contain the necessary components, directives, and services for each specific feature.

Components

Angular Material provides a wide range of components that can be used to build various parts of your UI. In this section, we will explore some of the commonly used components in Angular Material.

Buttons

Buttons are a fundamental UI element in any application. Angular Material provides a set of pre-styled buttons that can be easily customized and used in your application.

To use the MatButtonModule in your component, import it from @angular/material/button and add it to the imports array of your module, as shown in the previous section.

In your component's HTML template, you can use the mat-button directive to create a button:

<button mat-button>Click me</button>

This will render a button with the default Material design styles. You can also add additional classes or styles to customize the button further.

Cards

Cards are a versatile component that can be used to display various types of content, such as images, text, and buttons. Angular Material provides the MatCardModule for creating cards in your application.

To use the MatCardModule, import it from @angular/material/card and add it to the imports array of your module, as shown in the previous section.

In your component's HTML template, you can use the mat-card directive to create a card:

<mat-card>
  <mat-card-header>
    <mat-card-title>Card Title</mat-card-title>
    <mat-card-subtitle>Card Subtitle</mat-card-subtitle>
  </mat-card-header>
  <img mat-card-image src="image.jpg" alt="Image">
  <mat-card-content>
    This is the content of the card.
  </mat-card-content>
  <mat-card-actions>
    <button mat-button>Button 1</button>
    <button mat-button>Button 2</button>
  </mat-card-actions>
</mat-card>

This will render a card with a title, subtitle, image, content, and actions. You can customize the card's appearance by applying CSS classes or using the available Angular Material directives and attributes.

Dialogs

Dialogs are popup windows that can be used to display additional information or prompt the user for input. Angular Material provides the MatDialogModule for creating dialogs in your application.

To use the MatDialogModule, import it from @angular/material/dialog and add it to the imports array of your module, as shown in the previous section.

In your component, you can use the MatDialog service to open a dialog:

import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';

@Component({
  selector: 'app-my-component',
  template: `
    <button mat-button (click)="openDialog()">Open Dialog</button>
  `
})
export class MyComponent {
  constructor(private dialog: MatDialog) {}

  openDialog() {
    const dialogRef = this.dialog.open(MyDialogComponent);

    dialogRef.afterClosed().subscribe(result => {
      console.log(`Dialog result: ${result}`);
    });
  }
}

In this example, we are using the MatDialog service to open a dialog. The open method takes a component as an argument, which will be used as the content of the dialog. You can also pass additional configuration options to customize the dialog's appearance and behavior.

Forms

Forms are an essential part of any application, and Angular Material provides a set of form components and directives that can be used to create forms with ease.

To use the form components and directives from Angular Material, you need to import the MatFormFieldModule and MatInputModule modules. Add these modules to the imports array of your module, as shown in the previous section.

In your component's HTML template, you can use the mat-form-field directive to create a form field:

<mat-form-field>
  <input matInput placeholder="Username">
</mat-form-field>

This will render a form field with a floating label and other styling enhancements. You can also use other form-related components and directives provided by Angular Material, such as mat-select, mat-checkbox, and mat-datepicker.

Icons

Icons are graphical representations of objects or actions and can be used to enhance the visual appearance and usability of your application. Angular Material provides a collection of icons that can be easily used in your application.

To use icons from Angular Material, you need to import the MatIconModule module. Add this module to the imports array of your module, as shown in the previous section.

In your component's HTML template, you can use the mat-icon directive to display an icon:

<mat-icon>favorite</mat-icon>

This will render an icon with the name favorite. You can find a list of available icons in the Angular Material Icons documentation.

Navigation is an important aspect of any application, and Angular Material provides a set of components and directives that can be used to create navigation menus, toolbars, and sidebars.

To use the navigation components from Angular Material, you need to import the MatToolbarModule and MatMenuModule modules. Add these modules to the imports array of your module, as shown in the previous section.

In your component's HTML template, you can use the mat-toolbar directive to create a toolbar:

<mat-toolbar color="primary">
  <span>My App</span>
  <span class="spacer"></span>
  <button mat-icon-button>
    <mat-icon>menu</mat-icon>
  </button>
</mat-toolbar>

This will render a toolbar with a title and a menu button. You can customize the toolbar's appearance and behavior using the available directives and attributes.

Tables

Tables are a common way to display tabular data in an organized and readable format. Angular Material provides the MatTableModule for creating tables in your application.

To use the MatTableModule, import it from @angular/material/table and add it to the imports array of your module, as shown in the previous section.

In your component's HTML template, you can use the mat-table directive to create a table:

<mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let element">{{ element.name }}</mat-cell>
  </ng-container>
  <ng-container matColumnDef="email">
    <mat-header-cell *matHeaderCellDef>Email</mat-header-cell>
    <mat-cell *matCellDef="let element">{{ element.email }}</mat-cell>
  </ng-container>

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

This will render a table with two columns (name and email). You can customize the table's appearance and behavior using the available directives and attributes.

Theming

Angular Material provides a powerful theming system that allows you to easily customize the look and feel of your application.

Customizing themes

Angular Material comes with pre-built themes that you can use out of the box. However, you can also customize these themes to match your brand or design requirements.

To customize a theme, you can use the mat-palette and mat-theme directives. The mat-palette directive defines a set of colors that can be used in your application, while the mat-theme directive applies the defined colors to specific components.

Here is an example of how to customize the primary and accent colors of your application:

@import '~@angular/material/theming';

$my-app-primary: mat-palette($mat-indigo);
$my-app-accent: mat-palette($mat-pink, A200, A100, A400);

$my-app-theme: mat-light-theme($my-app-primary, $my-app-accent);

@include mat-core();

@include mat-button-theme($my-app-theme);
@include mat-card-theme($my-app-theme);
@include mat-dialog-theme($my-app-theme);
// ... include other component themes

@include mat-theme($my-app-theme);

In this example, we define two color palettes ($my-app-primary and $my-app-accent) using the mat-palette function. We then create a theme ($my-app-theme) using the mat-light-theme function, passing the primary and accent palettes.

Finally, we include the core Material styles using the mat-core mixin, and apply the theme to specific components using the mat-button-theme, mat-card-theme, mat-dialog-theme, and other component-specific mixins. The mat-theme mixin applies the theme to the entire application.

Creating your own theme

In addition to customizing the pre-built themes, you can also create your own custom theme from scratch. To create a custom theme, you can define your own color palettes, typography styles, and other theme variables.

Here is an example of how to create a custom theme:

@import '~@angular/material/theming';

$my-app-primary: mat-palette($mat-indigo);
$my-app-accent: mat-palette($mat-pink, A200, A100, A400);

$my-app-theme: (
  color: (
    primary: $my-app-primary,
    accent: $my-app-accent
  )
);

@include mat-core();

@include mat-button-theme($my-app-theme);
@include mat-card-theme($my-app-theme);
@include mat-dialog-theme($my-app-theme);
// ... include other component themes

@include mat-theme($my-app-theme);

In this example, we define our own primary and accent color palettes ($my-app-primary and $my-app-accent), and create a theme ($my-app-theme) using the defined palettes.

We then include the core Material styles using the mat-core mixin, and apply the theme to specific components using the mat-button-theme, mat-card-theme, mat-dialog-theme, and other component-specific mixins. The mat-theme mixin applies the theme to the entire application.

Layout

Angular Material provides a flexible and responsive grid system that can be used to create layouts of varying complexity.

Grid system

The grid system in Angular Material is based on flexbox, which allows you to easily create responsive layouts that adapt to different screen sizes and orientations.

To use the grid system, you can use the mat-grid-list directive in your component's HTML template:

<mat-grid-list cols="3" rowHeight="2:1">
  <mat-grid-tile *ngFor="let item of items">
    <img src="{{ item.imageUrl }}" alt="{{ item.description }}">
    <mat-grid-tile-footer>{{ item.title }}</mat-grid-tile-footer>
  </mat-grid-tile>
</mat-grid-list>

In this example, we are creating a grid list with 3 columns and a row height ratio of 2:1. We use the mat-grid-tile directive to define each grid tile, which contains an image and a footer.

You can customize the number of columns, row height, and other properties of the grid list and grid tiles to create the desired layout.

Responsive design

Angular Material's grid system supports responsive design out of the box, allowing you to easily create layouts that adapt to different screen sizes and orientations.

To create a responsive layout, you can use the fxLayout directive provided by the Angular Flex Layout library. This library is recommended by Angular Material for creating responsive layouts.

First, install the Angular Flex Layout library by running the following command in your terminal:

npm install @angular/flex-layout

Then, import the FlexLayoutModule into your module and add it to the imports array:

import { NgModule } from '@angular/core';
import { FlexLayoutModule } from '@angular/flex-layout';

@NgModule({
  imports: [
    // ...
    FlexLayoutModule
  ],
  // ...
})
export class AppModule { }

After importing the FlexLayoutModule, you can use the fxLayout directive to create responsive layouts. Here is an example:

<div fxLayout="row" fxLayout.xs="column">
  <div fxFlex="50" fxFlex.xs="100">Item 1</div>
  <div fxFlex="50" fxFlex.xs="100">Item 2</div>
</div>

In this example, we are creating a layout with two items. On larger screens (row layout), each item takes up 50% of the available space. On smaller screens (column layout), each item takes up 100% of the available space.

You can use the fxFlex directive to control the size of each item and the fxLayout.xs directive to specify the layout for extra-small screens.

Animations

Angular Material provides seamless integration with Angular's animation system, allowing you to easily add animations to your Angular Material components.

Using Angular animations with Angular Material

To use Angular animations with Angular Material, you need to import the BrowserAnimationsModule module into your application. This module enables support for animations in Angular Material components.

Open your app.module.ts file and add the following import:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [
    // ...
    BrowserAnimationsModule
  ],
  // ...
})
export class AppModule { }

After importing the BrowserAnimationsModule, you can use Angular's animation system to define animations for Angular Material components.

Here is an example of how to animate a button:

import { Component } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'app-my-component',
  template: `
    <button [@myAnimation]="buttonState" (click)="toggleState()">Toggle</button>
  `,
  animations: [
    trigger('myAnimation', [
      state('state1', style({ opacity: 1 })),
      state('state2', style({ opacity: 0 })),
      transition('state1 <=> state2', animate('500ms ease-in-out'))
    ])
  ]
})
export class MyComponent {
  buttonState = 'state1';

  toggleState() {
    this.buttonState = (this.buttonState === 'state1') ? 'state2' : 'state1';
  }
}

In this example, we define an animation using the trigger function from Angular's animation module. The animation has two states (state1 and state2) and transitions between them using the transition function.

We then bind the animation to the button using the [@myAnimation] syntax. The animation is triggered when the button is clicked, and the toggleState method updates the button's state.

You can define animations for other Angular Material components in a similar way, using the available animation functions and directives.

Conclusion

In this tutorial, we explored the various components and features of Angular Material and learned how to use them effectively in our Angular applications. We covered topics such as installation, importing modules, using components, customizing themes, creating layouts, and adding animations.

Angular Material provides a comprehensive set of UI components that can help speed up the development process and create visually appealing and user-friendly UIs. By following the guidelines and best practices provided by Angular Material, you can build beautiful and responsive UIs with ease.