Shared Module Share component and Material Modules efficiently throughout the app

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
Get Unlimited PRO Access

OR


*Enrollment provides full access to this course (and updates) for life.

Create a shared module to avoid duplicate imports and exports of common Angular Material features.

The SharedModule exports all declarations and modules so they can be consumed in other feature modules.

The SharedModule exports all declarations and modules so they can be consumed in other feature modules.

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.

file_type_ng_component_ts 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.

file_type_ng_component_ts 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 

Questions?

Ask questions via GitHub below OR chat on Slack #questions