How do I rectify importing all components of Angular Material from a single file, to avoid redundancy?

58 Views Asked by At

I am working on a project using the PEAN stack and have installed Angular's latest version. I have stored all modules of Angular Material in a file called 'material.module.ts' so that I don't need to import every single module repeatedly in all components. But the Angular Material tags are not working although the code seems fine.

material.module.ts (stored in the folder 'material' and used JUST to import modules, no other purpose and NOT a component) -

login.module.ts ('login' is a component to display a login screen) -

login.component.html -

output in localhost:4200 (can notice that 'mat-button' is not working) -

I cross-checked my package.json file with a GitHub repository I am using for inspiration, and it is fine. Help!

2

There are 2 best solutions below

2
Daniel Vágner On

enter image description here

In the provided picture, you have imported LoginComponent, but the component itself is not included in the declarations array. Therefore, it will not be able to utilize imports like LoginRoutingModule or MaterialModule. Is LoginComponent declared in a different module?

For your standalone component without a module.

import { Component, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NaterialModule} from '../material/material.module';

    
    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.scss'],
      standalone: true, // This makes the component standalone
      imports: [
        CommonModule,
        MaterialModule
      ],
      providers: [
        CustomService
      ]
    })
    export class LoginComponent {
      // Component logic
    }
0
bottletyre On

Create a material.module.ts file importing all Material Packages:

import {MatSnackBarModule} …
import { CUSTOM_ELEMENTS_SCHEMA, ModuleWithProviders, NgModule } from '@angular/core';

@NgModule({
    imports:[MatSnackBarModule],
    exports:[MatSnackBarModule],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class MaterialModule {
    static forRoot(): ModuleWithProviders<MaterialModule> {
        return {
            ngModule: MaterialModule,
        };
    }
}

In App.module.ts,

Imports:[
    MaterialModule.forRoot(),
    ],
schemas: [CUSTOM_ELEMENTS_SCHEMA],

Please refer this article for reference. https://angular.io/guide/deprecations#modulewithproviders-type-without-a-generic