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.

PS: Let us deep analyse  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. We’ll see an error if the rootComponent is not a standalone component, for that we’ll need to add standalone: true into the @Component metadata.

we’ll also see the options?: ApplicationConfig | undefined which is an interface containing only a providers property.

This is where we can then pass any providers we want to make available in our components and children ( for example with the help of importProvidersFrom() method) .

example:

bootstrapApplication(AppComponent, {
  providers: [importProvidersFrom(HttpClientModule), AuthService],
}).catch((err) => console.error(err));

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *