Configuring routes

The routes have information about selecting the view to render when a user clicks on a link for navigation. The following code snippet shows how to configure routes in app.module.ts:

import { RouterModule } from '@angular/router';
RouterModule.forRoot([
{
path: 'about',
component: AboutComponent
},
{
path: 'contact',
component: ContactComponent
}
])

Here, we have configured two routes that help the user navigate to the about and contact views when clicked on. Routes are basically a collection of route definitions. The value of the path defined identifies the component to be instantiated when the URL in the browser matches the path. Then, the instantiated component will take care of rendering the view.

Now, we need to add the configured routes to the AppModule, import the RouterModule from @angular/router, and add it to the imports section of @NgModule, as described:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './heroes.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{
path: 'about',
component: AboutComponent
}
])
],
declarations: [
AppComponent,
AboutComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Here, the forRoot() method provides router service providers and directives to perform navigation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.154.208