Using Material components in Angular 2

P1xt
P1xt’s Blog
Published in
2 min readMar 8, 2017

--

Figuring out how to incorporate Material Design components in Angular 2 can be a tricky prospect — if you are also serious about automated testing. There is great documentation on setting up Material, but it actually takes a fair bit of research to figure out how to ensure that incorporating a <md-toolbar> won’t cause ng test to start throwing a myriad of nigh unintelligible errors. I’ve done that research :D

Basic Setup with Angular CLI

(this assumes you have a recent version of node — I’m using v7, v6 would work as well).

Install Angular CLI

npm install -g @angular/cli

Create a new project

ng new <your-project-name>

Install the Angular Material components

(you can skip the hammerjs install if you don’t intend to use sliders)

npm install --save @angular/material
npm install --save hammerjs

Import the Angular Material NgModule

Look in the project you created with ng new above. There should be a src/app/app.module.ts file. You need to import the Material module and add it to the @NgModule imports and import hammerjs.

import { MaterialModule } from '@angular/material';import 'hammerjs';

@NgModule({
imports: [MaterialModule],
...
})

Add a Material theme to your Application

I recommend looking at the official docs for this, they’re awesome.

Start using Material in your Components

It’s as simple as adding a md-toolbar where you want one. Again the official docs are amazing. For every component, there’s a wealth of information describing it and how you’d use it, plus there are example code snippets you can copy for your own use.

And, then, you realize all your tests broke

At this point, everything should be working, you’ve bootstrapped your app, you’ve integrated Material into it, you’re using the Material components, and you run ng-test and are greeted with a wall of red.

The fix you’re looking for is this:

  • import Material Module into your test spec file
  • add imports:[MaterialModule.forRoot()] into the object you’re using to configure your TestBed

Here’s a snippet showing this in action:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MaterialModule } from '@angular/material'; // add this line
import { HeaderComponent } from './header.component';

describe('HeaderComponent', () => {
let component: HeaderComponent;
let fixture: ComponentFixture<HeaderComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
imports:[MaterialModule.forRoot()], // and this line
declarations: [ HeaderComponent ]
})
.compileComponents();
}));
});

Happy Coding :D

--

--