Standalone Components in Angular
Standalone Components is a feature that deals with the boiletplate code that we
have to currently write in a typical Angular app. Namely, it enables us to
create components without dealing with the modules and all their
declarations, imports, and so on. We can actually get rid of modules entirely,
even the AppModule
! That makes Angular a bit more similar to React or Vue.js,
which do not use the module system and are much leaner to work with.
Standalone components can be mixed with the “classic” NgModule style.
Example
Standalone components can’t be declared in any module. standalone: true
makes
it recognizable globally.
There are two ways to use standalone components in other components:
- new, when the parent component is also standalone
- “legacy”, with
NgModule
Standalone Parent
This way is very similar to how we’d do it in Vue.js.
Legacy Parent
Since standalone components can be mixed with NgModule-declared components, there’s a way to use standalone components in such “legacy” components.
First, we need to import the standalone component in our parent component’s module:
Now, the legacy component can make use of MyComponent
in its template, as it
typically would in “legacy” NgModule-based world.
Importing Modules
The standalone components may not only import other standalone components, but also whole modules! It is useful when our app uses some “legacy” entities that are exported by some module(s). To use these entities, our component has toimport the module.
If standalone component is the only thing that uses the imported module, that module does not need to be imported in any other module, as it would typiclaly be the case.
Standalone Root Component
We can get rid of modules entirely, including the main AppModule
. Without that
module though, we need a different way of bootstrapping our app with the
AppComponent
:
As a reminder, here’s the “legacy” way:
Dependency Injection
With modules being gone, we need another way of providing services globally.
Well there is the @Injectable
constructor, but it’s not everyone’s favorite to
provide service from the service itself.
We can use the new bootstrapApplication
and it’s second parameter:
MyService
will be available globally.
Routing and Lazy Loading
Lazy loading with standalone components is doable, it requires us to use a new
loadComponent
function in our routes to load the component dynamically.
The previously used loadChildren
function is still useful. Instead of loading
a module, we can use it to load a file containing child routes.