Following are the fundamental building blocks to creating a route.
AppRoutingModule
into AppModule
and add it
to the imports array.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module'; // CLI imports AppRoutingModule
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule // CLI adds AppRoutingModule to the AppModule's imports array
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
RouterModule
and Routes
into your routing
module.
The Angular CLI performs this steps automatically. The CLI also set up a Routes
array for your routes and configures the imports
and
exports
array
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'; // CLI imports router
const routes: Routes = []; // sets up routes constant where you define your routes
// configures NgModule imports and exports
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DefaultComponent } from './default/default.component';
Each route in this array is a JavaScript object that contains two properties. The first property path, defines the URL path for the route. The second property component, defines the component Angular should use for the corresponding path.
Use that component name with path, name, and data attribute in routes array in app-routing.module.ts file
const routes: Routes =
[
{
path: '',
children:
[
{
path: 'default',
component: DefaultComponent
},
],
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Now that you have defined your routes, you can add the component to your
application. First, add links to the components. Assign the anchor tag that you
want to add the route to the routerLink attribute. Set the value of the
attribute to the component to show when a user clicks on each link. Next, update
your component template to include