Display new routes under angular component
In Angular, you can display new routes under an existing component by using the router-outlet
directive and configuring the routes in the app-routing.module.ts
file.
Here's an example:
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
{
path: 'new-route',
component: NewRouteComponent,
children: [
{ path: '', component: NewRoute1Component },
{ path: 'sub-route', component: NewRoute2Component }
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In this example, we have a main route for the NewRouteComponent
and two child routes for NewRoute1Component
and NewRoute2Component
. The NewRouteComponent
will be displayed under the router-outlet
directive in the app.component.html
file.
app.component.html
<router-outlet></router-outlet>
new-route.component.html
<h1>New Route</h1>
<router-outlet></router-outlet>
In the new-route.component.html
file, we have another router-outlet
directive to display the child routes.
When you navigate to the new-route
route, the NewRouteComponent
will be displayed, and when you navigate to new-route/sub-route
, the NewRoute2Component
will be displayed.
You can also use the routerLink
directive to create links to the new routes:
<a [routerLink]="['/new-route']">New Route</a>
<a [routerLink]="['/new-route', 'sub-route']">Sub Route</a>
This will create links to the new-route
and new-route/sub-route
routes, respectively.