DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Implementing Micro Frontends in Angular: Step-By-Step Guide
  • Micro Frontends Architecture
  • Difference Between Bootstrap and AngularJS in 2022
  • Login With Google in Angular Firebase Application

Trending

  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  • Enforcing Architecture With ArchUnit in Java
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Modularize an Angular Application

How to Modularize an Angular Application

This article shows how lazy loaded Angular modules can be used to bring down the initial download size of an application.

By 
Sven Loesekann user avatar
Sven Loesekann
·
Jan. 04, 19 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
31.3K Views

Join the DZone community and get the full member experience.

Join For Free

Starting Point

The starting point is the AngularAndSpring project. It is an Angular 7 application with Material Components and a reactive Spring Boot backend. The initial download was more than 1.6 MB in size. The reason for the size of the initial download is that the app module includes all the code of the dependencies that are needed by the whole application. The goal is to create a smaller app module that starts with just a splash component and the services that are needed by more than one module. Then the application lazy loads the modules for the routes the user navigates to. The application has three parts:

  • The overview table. That shows a table of cryptocurrency quotes and has the login.
  • The details pages. That shows the current details of the quote and a chart.
  • The orderbook page. That shows the current orderbooks and requires to be logged in.

Each of the parts will become a module with one or more components. The modules will have only the required imports and be loaded if the user navigates to their route.

Modules

To bring down the size of the initial download, the lazy loaded modules of Angular are used. The modules are generated with the Angular CLI and the components are moved in the modules. TypeScript types help to do the refactoring. The required imports for the modules need to be added and the routes need to be created.

To add the modules, the Angular CLI was used:

ng generate module details --routing
ng generate module orderbooks --routing
ng generate module overview --routing

That generated the modules with module and route files inside of their directories.

Overview Module

The components quoteoverview and login have been moved into the module directory.

The route of the module is defined in the file overview-routing.module.ts:

const routes: Routes = [{
    path: '',
    component: QuoteoverviewComponent
    }];


@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class OverviewRoutingModule { }

Lines 1-4 define the empty path for the quoteoverview component.

Line 8 defines the route to be imported as a child route of the module.

The overview module has only one route because the login component is a modal panel. It is shown if you click on the login button.

The module is defined in the file overview.module.ts:

@NgModule({
    entryComponents: [
                      LoginComponent
                    ],
    imports: [
      CommonModule,
      OverviewRoutingModule,
      MatTableModule,
      MatToolbarModule,
      MatTabsModule, 
      MatButtonModule,
      MatDialogModule,
      MatFormFieldModule,
      MatInputModule,
      FormsModule,
      ReactiveFormsModule
    ],

  declarations: [
      LoginComponent,
      QuoteoverviewComponent
                 ]
})
export class OverviewModule { }

Lines 2-4 define the entryComponent login to enable the modal panel of the login component.

Lines 5-17 define the modules needed by the two components.

Lines 19-22 register the two components in the module.

Details Module

The components BsdetailComponent, Ibdetailcomponent, CbdetailComponent, and BfdetailComponenthave been moved in the Module directory.

The routes of the module need to be defined in the file details-routing.module.ts:

const routes: Routes = [
                        {path: 'bsdetail/:currpair', component: BsdetailComponent},
                        {path: 'ibdetail/:currpair', component: IbdetailComponent},
                        {path: 'cbdetail/:currpair', component: CbdetailComponent},
                        {path: 'bfdetail/:currpair', component: BfdetailComponent},
                        ];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DetailsRoutingModule { }

Lines 1-6 define the subroutes of the module. The ':currpair' is a route variable that defines the currency pair requested.

Line 9 defines the import of the routes as child routes of the module.

The module is defined in the file details.module.ts:

@NgModule({
  imports: [
    CommonModule,    
    FormsModule,
    ReactiveFormsModule,
    MatToolbarModule,
    MatRadioModule,
    MatButtonModule,
    DetailsRoutingModule,
    ChartsModule,
  ],
  declarations: [
    IbdetailComponent,
    CbdetailComponent,
    BsdetailComponent,
    BfdetailComponent
  ]
})
export class DetailsModule { }

Lines 2-10 define the modules that are required by the components.

Lines 11-16 list the components of the module.

Overview Module

The overview module has only the orderbooks component. It is ony accessable after login so it is not needed on the public part of the app.

The route is defined in the following code block:

const routes: Routes = [
{
    path: '',
    component: OrderbooksComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class OrderbooksRoutingModule { }

It is the same as in the overview module, execpt for the component.

The module is defined in the orderbooks.module.ts:

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MatToolbarModule,
    MatSelectModule,
    MatRadioModule,
    MatInputModule,
    MatCheckboxModule,
    MatButtonModule,
    MatListModule,    
    OrderbooksRoutingModule
  ],
  declarations: [    
    OrderbooksComponent    
  ]
})
export class OrderbooksModule { }

Lines 2-14 define the modules that need to be imported for the component.

Lines 15-17 registers the orderbooks component.

Application Module

The application module now has only the splash component and the services and is defined in the app.module.ts file:

@NgModule({
  declarations: [
    AppComponent,
    SplashComponent,
  ],
  imports: [    
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    HttpClientModule,
    MatProgressSpinnerModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Lines 2-5 list the components of the application module.

Lines 6-13 define the modules needed to show the SplashComponent and define the services.

The global routes are defined in the app-routing.module.ts file:

const routes: Routes = [
    {path: 'overview', loadChildren: './overview/overview.module#OverviewModule'},
    {path: 'details', loadChildren: './details/details.module#DetailsModule'},
    {path: 'orderbooks', loadChildren: './orderbooks/orderbooks.module#OrderbooksModule', canActivate: [AuthGuardService]},
    {path: '**', component: SplashComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Lines 1-6 define the global routes. The loadChildren entries reference the modules for the paths. The default path points to the Splash component. That loads the 'overview' path and shows a welcome message and a spinner while loading the overview module.

Line 9 defines the routes for the route module.

Summary

Modularizing the application has helped the startup performance and shows how bigger downloads can be split. In this case, the initial load was more than halved. If the files are gzipped it is below 300 kb.

TypeScript made it easy to split the code into ,odules. Splitting the templates was not as easy. The Angular compiler did not show the missing modules. The errors are shown at run time. It would be nice if Angular would have a feature that checks that all used modules are imported at compile time.

Splitting an existing application into modules is quite easy and takes only a reasonable amount of effort. The better approach is to start the development of an application with modules, placing related components in modules with a common base route and subroutes to the components. The required imports can then be added during the development process. That keeps the startup performance okay, with little extra cost.

application AngularJS

Opinions expressed by DZone contributors are their own.

Related

  • Implementing Micro Frontends in Angular: Step-By-Step Guide
  • Micro Frontends Architecture
  • Difference Between Bootstrap and AngularJS in 2022
  • Login With Google in Angular Firebase Application

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!