From the course: Angular: Building Large Applications

Introduction to Angular modules: Feature and shared - Angular Tutorial

From the course: Angular: Building Large Applications

Introduction to Angular modules: Feature and shared

- [Instructor] In Angular, modules allow us to organize code into distinct units, helping manage app complexity. Every Angular app starts with a root module, AppModule, but for large apps, we need to go beyond that with feature modules and shared modules. Feature modules are used to group code related to a specific functionality or section of your app. Think of it like focusing on a single aspect of your app, such as user management, product catalogs, or admin dashboards. For example, you might create a user module to manage user authentication and profile pages. Everything related to users, components, services, and routing can live inside that feature module, keeping things organized. Feature modules help in lazy loading, meaning the parts of your app that aren't needed right away can be loaded only when necessary. This improves performance by reducing the initial load time of your application. On the other hand, shared modules are created to house reusable components, directives, and pipes that can be shared across different parts of the application. These are not tied to any specific feature. For example, a shared module might include a button component, a modal, or custom pipes like CurrencyPipe. Instead of repeating code across multiple feature modules, you import these shared components into different parts of the app where they need it. But there is an important distinction. Shared modules don't import services unlike feature modules. This ensures that shared modules only focus on reusable UI elements and utilities. Services are typically added to feature modules or at the root level to avoid initializing multiple service instances. So, when should you use one over the other? Use a feature module when you need to encapsulate functionality that is specific to a domain or section of your app. For instance, if you're working on a project with an inventory system, you might have a project module that manages all product-related functionality and a user module for managing users. A shared module is ideal when you have reusable components or utilities that need to be used across multiple parts of your app. For example, a shared module with a custom date pipe and common UI elements can be imported by both the project module and user module to keep your code dry. In summary, feature modules help you organize domain-specific code, while shared modules promote reusability across the entire app. Understanding how to structure modules effectively will make your Angular apps scalable and easy to maintain.

Contents