Blog>
Snippets

Using Standalone Components with Angular Router

Demonstrate how to use standalone components as routes in Angular's routing module without the need for additional templates or components.
import { Routes } from '@angular/router';
import { StandaloneComponent } from './standalone.component';

export const routes: Routes = [
    { path: 'standalone', component: StandaloneComponent, standalone: true }
];
Defines an array of routes for the Angular Router, where 'StandaloneComponent' is imported and used directly as a route component. The 'standalone' property is set to true to indicate that this component does not require an Angular module.
import { enableProdMode, importProvidersFrom } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { routes } from './app.routes';

enableProdMode();
bootstrapApplication(StandaloneComponent, {
  providers: [
    importProvidersFrom(RouterModule.forRoot(routes))
  ]
});
Bootstraps the Angular application with the 'StandaloneComponent' as the root component. Imports and configures the RouterModule with the defined routes. This is necessary to correctly set up the Angular Router with standalone components.
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-standalone',
  template: `<h1>Welcome to the Standalone Component!</h1>
  <button (click)="navigate()">Navigate to Other Component</button>`
})
export class StandaloneComponent {
  constructor(private router: Router) {}

  navigate() {
    this.router.navigateByUrl('/other');
  }
}
Defines a 'StandaloneComponent' with a basic template and a method to navigate to another route. The 'Router' service is injected to enable programmatic navigation.