Angular Material - Material Module

In the last video we saw how to add a material button component to angular application, there were three simple steps, the first one is to import that component which is MatButtonModule, the second step is to add it to the imports array and the last step is to use it in the HTML.

Although this is perfectly fine there is a better-recommended approach and that approach is to create a separate module that deals with importing and exporting material components.

So let us use the CLI to generate a new module which we will call as material.

ng g m material

Once the command completes you should have a new folder called material inside the app folder and within the material folder you should have a file called material.module.ts. angular material module

In this module, we are only concerned with importing and exporting material components so let's just remove CommonModule, and you should add a new array which we will be called as exports. angular material module

Now let's do it the proper way, let's go and move the material button component that we had added previously from app.module.ts and paste it in our new material.module.ts module. The material.module.ts file should look like that. angular material module

Finally, the framework doesn't know yet about our material.module.ts. That's why we should add it to app.module.ts and don't forget to add it to imports array as well. angular material module

After restarting the server you should see the same result as previous, but this time we did the proper way.

To conclude what we have done is extracted material into its own module. From the next lecture to use any component all we have to do is import it and add it to the material.module.ts module, this approach isolates material code and also keeps the app.module.ts nice and clean.