Search code examples
angularangular-standalone-components

Angular 17: Lazy-Loading A Shared Component


(Most of the answers I've found are very out-of-date and don't deal with standalone components).

In my Angular application, I have multiple shared components that are standalone. Unfortunately, I cannot find a way to make them lazy load if they aren't a route that uses loadComponent() and import() in the routes definitions file.

So, I have this in my application:

src
- main
  - app
    - modules
      - shared
        - components
          - shared-component1.component.ts
          - shared-component2.component.ts

Is there a relatively easy way in modern Angular versions to lazy-load a shared, standalone Angular component?


Solution

  • You can achieve that with deferrable views. To lazy load the component, just place it inside a @defer block in the template like the following:

    @defer {
      <shared-component1 />
    }
    

    Make sure that the component is only loaded via @defer across the whole project, and not eagerly loaded somewhere else. (Thanks @Matthieu Riegler for pointing that out)