In this article you’ll learn how to bootstrap a standalone Angular application using standalone components, which is how to bootstrap Angular without an NgModule
.
The standalone component approach differs from using the NgModule
approach the moment we want to bootstrap.
With NgModule
, this is done via a bootstrapModule
function exported from the @angular/platform-browser-dynamic
package:
import { NgModule } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
@NgModule({...})
export class AppModule {}
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch((err) => console.error(err));
With standalone components, there are a few changes. Instead of using the @angular/platform-browser-dynamic
package, we’ll refactor it to @angular/platform-browser
instead.
This exposes to us a new function called bootstrapApplication
, which expects a @Component
instead of @NgModule
:
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
@Component({...})
export class AppComponent {}
platformBrowserDynamic()
.bootstrapApplication(AppComponent)
.catch((err) => console.error(err));
As this returns us a Promise
as well, we can also use it to catch any errors like with NgModule
.
What’s more is the function signature for bootstrapApplication
:
bootstrapApplication(rootComponent: Type<unknown>, options?: ApplicationConfig | undefined): Promise<ApplicationRef>
Here we expect a rootComponent
, which must be a standalone component. You’ll see an error if you’ve not passed in a standalone component, for that you’ll need to add standalone: true
into the @Component
metadata.
You’ll also see the options?: ApplicationConfig | undefined
which is an interface
containing only a providers
property.
This is where you can then pass any providers you want to make available in your components and children.
🚀 Want to learn even more awesome Angular practices?
Check out my new Angular Courses if you’re serious about taking your skills to the top! There’s so much about Standalone Components and all the new best practices in the course.
Thanks for reading, happy bootstrapping!