Angular Material Grid 🔲 (Example)

Angular 2+ Material Grid

When building SPA (Single Page Application), there is really big chance you will run in to “Grid” issue. It can be some kind of dash board, it can be pinteres like grid, or just contact cards. I think there is no silver bullet. Way to go is flex for shure, but when you already utilising Material, you can use mat-grid-list. And this article will be about it.

Material Grid List

Grid lists are great, because can help improve the visual comprehension of the content. Mat-grid-list is a two-dimensional list view that arranges cells into grid-based layout. If you know angularjs data grid called UI Grid this is similar. A grid list consists of cells in vertical and horizontal layout. Grid lists are great, because can help improve the visual comprehension of the content.

Example

In this example we will try to create simple grid demo as is in Material documentation.

Angular 2+ Material Grid

We should start with importing necessary modules in app.module.ts:

import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import { MatGridListModule, MatToolbarModule } from '@angular/material'; // <----- HERE
import {AppComponent} from './app.component';
@NgModule({
imports: [
BrowserModule,
CommonModule,
MatToolbarModule,
MatGridListModule, // <----- HERE
BrowserAnimationsModule
],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: []
})
export class AppModule {}

Next thing we need to do is create tiles model in app.component.ts:

import {Component} from '@angular/core';
@Component({
selector: 'material-app',
templateUrl: 'app.component.html'
})
export class AppComponent {
tiles = [
{text: 'One', cols: 2, rows: 1, color: '#142A5C'},
{text: 'Two', cols: 1, rows: 1, color: '#B7A0E8'},
{text: 'Three', cols: 1, rows: 2, color: '#FF0000'},
{text: 'Four', cols: 3, rows: 1, color: '#D9EDD9'},
];
}

Now we can display our tiles in our template (app.component.html):

<mat-grid-list cols="4" rowHeight="100px">
<mat-grid-tile
*ngFor="let tile of tiles"
[colspan]="tile.cols"
[rowspan]="tile.rows"
[style.background]="tile.color">
{{tile.text}}
</mat-grid-tile>
</mat-grid-list>

And that’s it! Whole example is taken and edited from official Material Grid documentation, where you should continue for more informations.

And of course here is the whole plunker:

Buy me a coffeeOut of coffee 😱, please help!