1. 程式人生 > >10 Helpful Tips I Wish I Knew Before I Started Using Angular (≥2)

10 Helpful Tips I Wish I Knew Before I Started Using Angular (≥2)

2. NgModules and lazy loading for performance

When we first started using Angular, NgModules were not a part of the API (it was first introduced in 2.0.0-RC5). There was one mono-app (apps are now called projects) where you would have added all your services and components. If you had a single page application (SPA) then this seemed like a reasonable way to structure everything. But wait! Do you really, truly, need EVERYTHING when the page loads? If your app (project) is complicated enough, then probably not. Even if it’s not that complicated, why not load and bootstrap the core of Angular as quickly as possible, and then load your application code? Lazy loading as much of your code as possible is a great way to improve speed, and the best way to lazy load your code is with NgModules.

If you want to utilize lazy loading, look no further than feature modules. Each feature module contains a set of components and services. You can then use the feature module to break down the initial bundle size by easily splitting the code and dynamically loading it based on the route (as seen here

https://angular.io/guide/feature-modules) or based on any arbitrary conditions (as seen here https://stackblitz.com/edit/angular-gitter-bdeyzm)

Shared modules are probably something you’ve already run into, but they stem from not being able to declare a component in more than one NgModule. You declare the component in the shared module, and then import the shared module into other modules.

A root module is the module you use to bootstrap the components to the page. You have some different options for bootstrapping components, outlined in the bootstrapping section (#6) below.