How well does a collective Angular Material module perform when it incorporates numerous Component modules?

Have you ever explored the Angular Material component usage guide? It recommends creating a shared module to include multiple components. I'm curious about how shared modules are utilized.

Utilizing an Angular Shared Module

import {MatButtonModule} from '@angular/material/button';
import {MatCheckboxModule} from '@angular/material/checkbox';

@NgModule({
  imports: [MatButtonModule, MatCheckboxModule],
  exports: [MatButtonModule, MatCheckboxModule],
})
export class MyOwnCustomMaterialModule { }

Imagine this shared module includes a multitude of component modules, perhaps around 50 or more. If you import this shared module into another module where only one material module is needed, will there be any impact on performance such as loading time? Are shared modules cached for efficiency?

Answer №1

The FAQs on NgModules provide detailed information.

Importing the Same Module Twice

No need to worry about importing the same module multiple times. Angular evaluates the module only once, caching it for future use even in hierarchical setups.

Circular references between NgModules are not supported by Angular, so avoid situations where Module 'A' imports Module 'B', which then tries to import Module 'A' again.


Taking advantage of performance benefits involves selectively adding necessary Angular Material component modules to your application.

The deprecation notice regarding Angular Material beta.3 emphasizes:

MaterialModule Deprecation

MaterialModule (and MaterialRootModule) have been marked as deprecated due to tree-shaking issues. Users are advised to create custom "Material" modules that include only required components to reduce code size effectively.

This advice remains relevant in 2019 as stated in the Angular Material getting started guide:

To minimize code bloat, consider creating a dedicated NgModule specifically for importing and re-exporting the necessary Angular Material components within your application for seamless integration with other modules.

Answer №2

Reconsidering the Use of Shared Material Module

Upon reflecting on previous responses recommending the use of a shared material module in Angular development, I decided to put the suggested approach to the test. However, after reading this insightful article, my perspective shifted:

Reconsidering the Use of Shared Material Module

The article pointed out that incorporating all Angular modules into one shared module may not be as effective as initially thought. The testing results speak for themselves.

Furthermore, it was highlighted that even other sources, like this Getting Started with Angular Material guide, do not currently recommend creating a separate module solely for exporting Angular Material modules.

Answer №3

A while ago, I had a similar question and stumbled upon an article that really helped me out: Avoiding Common Confusions with Modules in Angular, written by Max Koretskyi aka Wizard

The Concept of Module Caching

Every now and then, a developer raises concerns on stackoverflow about the potential duplication of module code when importing it to both lazy and non-lazy modules. This assumption is quite common, but fret not as all existing module loaders have mechanisms in place to cache the modules they load.

When SystemJS loads a module, it stores it in the cache. Subsequent requests for this module will retrieve it from the cache rather than making another network request. This caching process occurs for each module.

For instance, when working with Angular components, you typically import the Component decorator from the angular/core module:

import { Component } from '@angular/core';

Despite referencing the same package multiple times in your application, SystemJS only loads the angular/core package once and caches it for future use. A similar approach is taken by Webpack if you utilize angular-cli or configure webpack manually. The module code is included only once in a bundle and assigned an ID. Other modules then import symbols from this module using the assigned ID.

I highly recommend reading through the entire article and jotting down some personal notes as it greatly aided me in understanding Angular's architecture. The article is well-written and explains the concepts clearly, so there's no need for me to rephrase it.


On another note, a SharedModule is utilized for sharing components, pipes, and directives. While you may import modules from third-party libraries and export them for sharing, essentially, you are disseminating the components, pipes, and directives declared within the third-party lib's module (such as Angular Material's modules).

The SharedModule gets compiled into main-abcd1234.js, somewhat resembling the compilation log seen midway through this post :

https://i.sstatic.net/oGMsW.png

The main-abcd1234.js file is loaded at the start of the app. You can confirm this by checking the network tab during your app's initial load.

In my current project, the size isn't too substantial, just a few hundred kilobytes. To test if your "app size" increases, try importing the SharedModule into a module X that uses only one component from the shared module and observe if module X's compiled bundle size changes. It likely won't.

If you're curious about how chunks are named, you can set namedChunks to true in angular.json and execute ng serve --prod to avoid seeing encoded characters.

Cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React component TypeScript props validation problem

Imagine having a button that comes in two variants: contained or outlined. How can you ensure that only the specific colors for each variant are allowed to be selected? const variants = { contained: { red: "bg-red-600 text-red-100 active: ...

Function returning promise asynchronously, but caller function failing to resolve the promise

I have been researching similar items without success and I realize that I need a better understanding of promises, but I am facing some challenges. My project involves Ionic 4/Angular 8 with an Azure-based backend. I am trying to display images from Azur ...

The challenge of extending a TypeScript generic to accept an Array type with unrelated elements

I have a function that resembles the following mock: // All properties in this type are optional. interface MyType { a?: string } // The return result type of `cb` is kept as the final result type. const f = <T extends ReadonlyArray<MyType>> ...

The server encountered an issue with starting the ANCM Out-Of-Process, resulting in HTTP Error 502

We currently have two projects in progress. One involves a Web API built on .NET Core 2.2.6 and an Angular 8 Single Page Application integrated within .NET Core 2.2.6. Both projects have been deployed on IIS 7 with the Web API functioning properly, but the ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Errors in the @babel/types during the ng build process in Angular version 8.2.14

When I execute the command 'ng build' for my Angular App, I encounter the following errors: ERROR in ../node_modules/@types/babel-types/index.d.ts:1769:96 - error TS1144: '{' or ';' expected. 1769 export function assertArrayE ...

What is the best way to share a parent component's input value with two child components using the Angular 4 Router module?

I am currently developing a simple Airbnb search feature. The project consists of 3 main components: SearchComponent, which contains the search form; ListingComponent, responsible for listing Airbnb rentals; and MapComponent, displaying markers on a Google ...

Can you identify the specific syntax for a 'set' function in TypeScript?

I have a TypeScript function that looks like this: set parameter(value: string) { this._paremeter = value; } It works perfectly fine. For the sake of completeness, I tried to add a type that specifies this function does not return anything. I experimen ...

Employing the keyof operator with the typeof keyword to access an object

What data type should be used for the key variable? I am encountering an error stating that "string" cannot be used to index the type "active1: boolean, active2". const [actives, setActives] = React.useState({ active1: false, active2: false, }); con ...

Issue stemming from reactivity causing difficulties with Vuex data mutation within actions

I have a Vuex store action that needs to interact with the API using new data for updating purposes. My goal is to create a separate object that mirrors an existing value in the store, allowing me to manipulate it without affecting reactivity. However, w ...

The property 'fullName' is assumed to have type 'any' due to the missing parameter type annotation in its set accessor

While enrolled in a JS course, I encountered the following code that was not functioning properly when added. Instead of returning the expected result, it returned 'undefined.' After investigating further, I identified that the issue lies within ...

Managing business logic in an observable callback in Angular with TypeScript - what's the best approach?

Attempting to fetch data and perform a task upon success using an Angular HttpClient call has led me to the following scenario: return this.http.post('api/my-route', model).subscribe( data => ( this.data = data; ...

Encountering an issue: "Failed HTTP response while trying to access https://localhost:44328/api/AllItProjectsLists/Index: 0 Error Message Unknown"

I am completely new to working with Angular. I have been working on a small application that is supposed to display a list of projects retrieved from a database on the Angular side. To achieve this, I am making a call from Angular to .NET Core 2.2. The dat ...

I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key. obj1 = { name: 'John', address: 'Cairo' } obj2 = { num : '1', address: 'Egypt' } After merging, the r ...

Issues with Angular2 Router functionality not functioning as expected

I have been facing an issue while trying to set up a basic Angular2 application with login functionality using Typescript. Despite defining the Router, I encounter an error when trying to access the specified URL in a browser. The error message reads: Can ...

The AWS S3 CreatePresignedPost function is failing to generate certain essential fields

Currently, I am facing an issue with the generation of a presigned post for allowing browser privileges to upload/delete a specific file from a bucket. It appears that the createPresignedPost function is not populating some of the required fields, whereas ...

The "ngx-places" directive does not have an "exportAs" setting

I recently added the ngx-google-places-autocomplete module to my project. However, upon configuring it, I encountered the following error: core.js:14597 ERROR Error: Uncaught (in promise): Error: Template parse errors: There is no directive with "expo ...

Retrieve the value of [routerLinkActive] in the component's class

Recently, I've been working on a tab component called TabComponent and it includes the following HTML template: <a [routerLink]='link' [routerLinkActive]="[is-active]">link label</a> <button>Close tab</button> The c ...

Firebase login success callback not getting invoked

I have set up routes, the AuthGuard, and Firebase login in my project. I am using callbacks to handle the success and failure of the Firebase login process. successCallback(signInSuccessData) { console.log("Received with Success!"); } errorCallback(e ...

Navigating SSL certificate prompts in Protractor

Our programs utilize SSL certificates and we are unable to bypass Chrome's prompt for selecting a certificate. We would be satisfied with simply choosing the one certificate needed. Attempts have been made using this code: capabilities: { browser ...