Menu Close

Angular Material — Snackbar and Sort Header

Angular Material is a popular UI framework based on Material Design for Angular.

In this article, we’ll look at how to use Angular Material into our Angular project.

Snackbar

A snackbar is a container for notification.

The MatSnackBar service can be used to add it.

For example, we can write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatButtonModule } from '@angular/material/button';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatSnackBarModule,
    MatButtonModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'snack-bar-component-example-snack',
  template: 'pizza party',
  styles: [`
    .example-pizza-party {
      color: hotpink;
    }
  `],
})
export class PizzaPartyComponent { }

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  durationInSeconds = 5;

  constructor(private _snackBar: MatSnackBar) { }

  openSnackBar() {
    this._snackBar.openFromComponent(PizzaPartyComponent, {
      duration: this.durationInSeconds * 1000,
    });
  }
}

app.component.html

<div>
  <button mat-stroked-button (click)="openSnackBar()">
    Pizza party
  </button>
</div>

We add the MatSnackbarModule to let us add the snackbar.

Then in app.component.ts , we inject the MatSnackBar service into AppComponent to let us call the openFromComponent method with a component with the snackbar content.

The duration is in milliseconds.

In the template, we have a button to open the snackbar by calling the openSnackBar method.

Sort Header

We can add the sort header component to let us sort state and display tabular data.

For example, we can write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatSortModule } from '@angular/material/sort';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatSortModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { Sort } from '@angular/material/sort';

interface Dessert {
  name: string,
  calories: number,
  fat: number
}

const compare = (a: number | string, b: number | string, isAsc: boolean) => {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  desserts: Dessert[] = [
    { name: 'Frozen yogurt', calories: 159, fat: 6 },
    { name: 'Ice cream sandwich', calories: 237, fat: 4 },
    { name: 'Eclair', calories: 262, fat: 16, },
    { name: 'Cupcake', calories: 305, fat: 4, },
    { name: 'Gingerbread', calories: 356, fat: 16 },
  ];

  sortedData: Dessert[];

  constructor() {
    this.sortedData = this.desserts.slice();
  }

  sortData(sort: Sort) {
    const data = this.desserts.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'calories': return compare(a.calories, b.calories, isAsc);
        case 'fat': return compare(a.fat, b.fat, isAsc);
        default: return 0;
      }
    });
  }
}

app.component.html

<div>
  <table matSort (matSortChange)="sortData($event)">
    <tr>
      <th mat-sort-header="name">Dessert (100g)</th>
      <th mat-sort-header="calories">Calories</th>
      <th mat-sort-header="fat">Fat (g)</th>
    </tr>

    <tr *ngFor="let dessert of sortedData">
      <td>{{dessert.name}}</td>
      <td>{{dessert.calories}}</td>
      <td>{{dessert.fat}}</td>
    </tr>
  </table>
</div>

We add the MatSortModule so that we can use the matSort directive into the table element.

Then we can click on the table header to sort the columns.

When we click on the header, the matSortChange event is emitted.

When it’s emitted, sortData is called.

Then, in app.component.ts , we call sort on the data and call our compare function to do the sorting.

Conclusion

We can add a snackbar and a sort header to sort table columns with Angular Material.

Posted in Angular, Angular material