Angular & MaterializeCSS

During the last year, I’ve developed numerous websites and mobile applications using the Angular framework. I’ve used numerous CSS frameworks as well such as Bootstrap, Ratchet, and Topcoat. But recently, a customer asked me to use MaterializeCSS. MaterializeCSS is a library of CSS and JavaScript code to easily create a material design experience for web applications. It’s quick, easy, and visually appealing. Unfortunately, getting some of the components to work with Angular proved difficult as the online documentation does not show how to setup Materialize for Angular. While most of the components do not require any JavaScript interaction by the developer, some components (such as select option lists or tabs) require initialization. The documentation says that tabs can be initialized by using:

var instance = M.Tabs.init(el, options);

Unfortunately, this won’t work in Angular as you’ll get numerous errors regarding undeclared variables. How can you hook this up properly?

First, declare the ‘M’ variable inside the page component below the imports. This will allow you to use the ‘M’ interface to MaterializeCSS from within your Angular code.

declare var M: any;

Next, get a reference to the object you are trying to interact with. This can be obtained by using a querySelector for the class of object you’re trying to initialize. For instance, tabs will be declared in HTML by assigning a class=”tabs” attribute to object. Once you have the object, you can initialize it by calling the appropriate method. This should all happen on the init method of your page object.

ngOnInit() {
  const elem = document.querySelector('.tabs');
  const options= {};
  M.Tabs.init(elem, options);
}

This is identical for any other object that requires MaterializeCSS initialization and can also be used to call any other functions in the MaterializeCSS framework.

With this information, you should be able to enjoy the benefits of Angular as well as the awesome UI elements of MaterializeCSS to their fullest!

Leave a Reply