Routing - 1
~30 mins
Task 1: RoutingModule
declartions: [
....
AppRoutingModule
]
Task 2: Add router outlet
<router-outlet></router-outlet>
Task 3: Add Routes
routes = [
{path:'home', component:HomeComponent},
{path:'login', component:LoginComponent},
{path:'', redirectTo:'login', pathMatch:'full'}
];
Task 4: Add Router Link
<a routerLink="login">Login</a>
(or)
<button type="button" routerLink="login"> Login </button>
Task 4: Test the Route URL
http://localhost:4200/login
Task 5: Navigate to route
constructor(private router:Router) { }
....
this.router.navigate(['login']);
//or
this.router.navigateByUrl('login');
Task 6: Get Router Params
routes = [
....
{ path:"users/:userId", component:UserComponent }
]
userId:number;
constructor(private route:ActivatedRoute) {
this.route.params.subscribe(params=>{
this.userId = params["userId"];
console.log("UserId:" + this.userId);
});
}
Task 6.1: Test Router Params
http://localhost:4200/users/123
Task 6.2: Navigate Route with params
let userId = 123;
this.router.navigate(['users/' +userId]);
Task 7: Get Router Query Params
routes = [
....
{ path:"user", component:ViewUserComponent }
]
userId:number;
constructor(private route:ActivatedRoute) {
this.route.queryParams.subscribe(params=>{
this.userId = params["userId"];
console.log("UserId:" + this.userId);
});
}
Task 7.1: Test Router Query Params
http://localhost:4200/user?userId=123