Bryan
Bryan

Reputation: 3009

Angular Material Not Working in Some Components

Sorry if this is hard to follow, but I'm confused why my code is working in some components, but not others. I imported MdButtonModule into my app.module.ts file and was able to get the following code to work in my app.component.html file:

<button md-button>Click Me!</button>

When I tried the same code in a component called shifts.component.html, it didn't work. shifts.component.ts is imported in shifts.module.ts and shifts.module.ts is imported in app.module.ts. It turns out that I had to import MdButtonModule into shifts.module.ts in order to use Angular Material buttons in shifts.component.html. Shouldn't I be able to use Angular Material buttons in any component if I import it in app.module.ts? Something doesn't seem right. What am I not understanding?

Upvotes: 2

Views: 2524

Answers (2)

Reza Taba
Reza Taba

Reputation: 1904

If you ever decided to create a separated module as suggested by @Nour, here's a better approach so you don't repeat the MatModules in the import/exports.

material.module.ts

import { NgModule } from '@angular/core';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatSnackBarModule } from '@angular/material/snack-bar';

const material: any[] = [
  MatTableModule,
  MatTabsModule,
  MatSnackBarModule
]

@NgModule({
  imports: [material],
  exports: [material]
})
export class MaterialModule { }

Upvotes: 0

Nour
Nour

Reputation: 1497

This piece of information taken from Official Angular Material

Step 3: Import the component modules

Import the NgModule for each component you want to use:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  ...
  imports: [MdButtonModule, MdCheckboxModule],
  ...
})
export class PizzaPartyAppModule { }

Alternatively, you can create a separate NgModule that imports all of the Angular Material components that you will use in your application. You can then include this module wherever you'd like to use the components.

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  imports: [MdButtonModule, MdCheckboxModule],
  exports: [MdButtonModule, MdCheckboxModule],
})
export class MyOwnCustomMaterialModule { }

Whichever approach you use, be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules.

Upvotes: 3

Related Questions