Since Angular 14, any Angular feature (component, pipe, or directive) can be created as “standalone.” This week, we will dive into what standalone components are, what feature they bring to the table, and how to use them.
One quick note before we start: Whenever you see the words “standalone components,” it really means “standalone components/pipes/directives.” Perhaps we should call those “standalone features,” but I’ll stick with the naming convention used by the Angular team so far, so I don’t stand… alone.
What’s a standalone component?
A standalone component is a component that doesn’t belong to any NgModule
. It can be imported on its own and used as-is.
For instance, in the past, we might have a ButtonComponent
and a ButtonDirective
in a ButtonModule
(just like Angular Material does). This means that if we want to use ButtonComponent
, we have to import the ButtonModule
in our AppModule
or feature module. This will make both ButtonComponent
and ButtonDirective
available for use in our app, even if you just use one of those features and don’t need the other.
Standalone components are different. They can be imported in a module just like other modules get imported in the array of imports
:
Importing only the features we need is always better for performance, as the build output will be smaller than if we import an entire module of dependencies. So that would be benefit number one of standalone components.
How to create a standalone component?
With the Angular CLI: ng generate component Button --standalone
We can also make an existing component standalone by adding the standalone: true
property in the @Component
decorator like so:
You can see that example in action here on Stackblitz.