Angular 6 Routing Tutorial
Now, let's make our 2 icons work when they're clicked. In order to do that, we need to visit the /src/app/app-routing.module.ts file.This is what it looks like:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
We need to import our components at the top, and add them to the Routes array shown on line 4 above.To do that, add the following:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UsersComponent } from './users/users.component';
import { DetailsComponent } from './details/details.component';
import { PostsComponent } from './posts/posts.component';
const routes: Routes = [
{
path: '',
component: UsersComponent
},
{
path: 'details/:id',
component: DetailsComponent
},
{
path: 'posts',
component: PostsComponent
},
];
We've imported our 3 components, and then defined three objects in the Routes array.The first object specifies that the UsersComponent will be the default component that loads on the root path. We leave the path value empty forthis.
The next route is for a user details section. We've specified a wildcard named id. We'll use this to fetch that value from the router in order to retrieve the correct user details.
Then another route for a component and path called posts.
Save this file, and the browser should now show:
Angular 6 Routing Tutorial
Reviewed by Pakainfo
on
August 08, 2018
Rating:
No comments: