🤝 Shared Module
Share component and Material Modules efficiently throughout the app
Create a shared module to avoid duplicate imports and exports of common Angular Material features.
Steps
Step 1 - Create a Module
command line
ng g module shared
Add it to the app module. It will be imported by all features in this app.
app.module.ts
import { SharedModule } from './shared/shared.module';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
SharedModule // <-- here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 2 - Consolidate Imports
Avoid duplication by consolidating your imports with the the spread syntax. We will be using the common material modules throughout the course. All Material modules listed below will be used in this app.
shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';
import { LayoutModule } from '@angular/cdk/layout';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { RouterModule } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { ShellComponent } from './shell/shell.component';
const components = [ShellComponent];
const modules = [
CommonModule,
MatButtonModule,
MatToolbarModule,
MatIconModule,
LayoutModule,
MatSidenavModule,
MatListModule,
MatMenuModule,
MatIconModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatSnackBarModule,
RouterModule
];
@NgModule({
declarations: [...components],
imports: [...modules],
exports: [
...components,
...modules,
]
})
export class SharedModule {}
Step 3 - Add a Component
command line
ng g component shared/shell --export