(Truly!?) Component oriented Angular application using Standalone components
If you have been following up Angular updates, you must have heard about Standalone
components introduced in Angular 14 in feature preview.
I have recently delivered a talk to Google I/O Calabar showcasing how to bootstrap a product idea using Standalone component approach.
What’s wrong with NgModule?
For a long time, there was a debate — why do we need NgModules? Many seasoned developers find NgModules approach bit complicated, whereas for newbie it is a test to comprehend. Though NgModule brings in many features like a single place to maintain service dependencies, logical grouping of components, providing encapsulation etc., there was an ask to make it optional and build Angular application directly component based.
Well, it is heard by the Angular team, and developers community, and Standalone
components have been introduced.
Comparing NgModule vs Standalone application
In traditional Angular application, the application is bootstrapped with NgModule and it’s bootstrap
property specifying the root component.
In a standalone approach@Component
decorator introduced new property standalone
which can be set to true
to mark it. The standalone components can survive without NgModule, we can get rid of AppModule. We can directly delete the app.module.ts
file.
The application start from main.ts,
and as we saw earlier, we provided AppModule
to bootstrap application. However, if we have deleted AppModule
, how we can tell Angular which one is our root component. To do so, we can call a new method bootstrapApplication
passing the root component and optional parameters specifying dependencies where routing can be specified.
Notice, how we are passing the routes. The importProvidersFrom
function extracts the required providers from RouterModule.fromRoot
. Why is that? Normally, we specify our routes in NgModules (AppRoutingModule), and pass it to AppModule
.
But, we have removed the AppModule
file itself. To specify routes to Angular’s Router
service, we need to use importProvidersFrom
. We can rename the app-routing.module.ts
file just app-routing.ts
and remove the AppRoutingModule
NgModule.
With these changes, we have converted our Angular application with only components. No NgModules! Of course, you can create, and have a mix of NgModules and standalone components, import other feature components, material design components, services, pipes into the Component itself.
In your actual work project, you should start gradually converting NgModules to standalone components instead of writing it from scratch.
You can find the complete source code with standalone components here.
The demo application is deployed here.
Cheers!