DEV Community

Alireza Razinejad
Alireza Razinejad

Posted on

Convert NgModule Angular app to Standalone Component

We are going to convert the fresh Angular app that is generated with Angular cli which is using NgModule to Standalone Component.

The code available on my Github profile.

Convert AppComponent to Standalone Component

To have standalone component we just need to pass standalone property to @Component() directive as with true value.

So the AppComponent will be looks like the following

import {Component} from '@angular/core';
import {RouterModule} from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `<router-outlet></router-outlet>`,
  imports: [RouterModule],
})
export class AppComponent {}
Enter fullscreen mode Exit fullscreen mode

Side note

As we are using `router-outlet` component to out put the routed views, we need to import `RouterModule`.

Other dependencies should be imported too.
Enter fullscreen mode Exit fullscreen mode

Remove AppModule

To be able to remove AppModule we need to move root initializations to main.ts.

To have cleaner way of managing routes, let's create separate file called routes.ts that exports first layer of route configs.

And it should be something like this

import {Routes} from '@angular/router';

const routes: Routes = [
  {path: '', redirectTo: 'appointment', pathMatch: 'full'},
  {
    path: 'appointment',
    loadComponent: () =>
      import('./app/pages/appointment/appointment.page')
        .then(mod => mod.AppointmentPage)
  }
];

export default routes;
Enter fullscreen mode Exit fullscreen mode

Side note

As you can see, here I've used loadComponent instead of loadChildren and, that's because the AppointmentPage is standalone component.

Update main.ts

Earlier the main.ts was responsible to bootstrap the AppModule and that was it!

But now, that we have the standalone AppComponent, it should bootstrap the application and also initialize the root provider modules. For example when we are going to import the RouterModule, we actually need to call forRoot method with passing the route configs to it.

So, the final main.ts would be something like this

import {enableProdMode, importProvidersFrom} from '@angular/core';

import { environment } from './environments/environment';
import {bootstrapApplication} from '@angular/platform-browser';
import {AppComponent} from './app/app.component';
import {RouterModule} from '@angular/router';
import routes from './routes';

if (environment.production) {
  enableProdMode();
}

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(
      RouterModule.forRoot(routes)
    )
  ]
})
  .catch(err => console.error(err));
Enter fullscreen mode Exit fullscreen mode

That's it! Now we have an Angular application which is base on Standalone Component.

Thank you for your time.

If you liked this post, I guess you would like my posts on Linkedin.

Top comments (0)