Can we add route automatically in app.routing.ts when component is created?

Viewed 1382

I want to add a route automatically in app.routing.ts file whenever new component is created.

1 Answers

With Angular CLI version 8.1 you can do:

ng g module home --route home --module app.module

ref: generating a module with angular cli

The command above will:

  1. Generate a lazy-loaded module called HomeModule

  2. Insert a lazy route in app.module.ts

  3. Generate an eager default route inside the HomeModule

  4. Generate a component that will handle the eager default route

In most cases you will need to edit the file by hand, but it's not difficult, just copy-paste app-routing and adapt it to your case. This is the example in the Angular web:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroesComponent } from './heroes/heroes.component';

const routes: Routes = [
  { path: 'heroes', component: HeroesComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Where 'heroes' will be the route to HeroesComponent, so when you write in a browser http://your-app-url/heroes it should display that component.

Cheers!

Related