Router and Navigation in Angular 4

Router and Navigation in Angular 4

1. Create Router Link

  <a routerLink="/post">Post</a>
  Example URL : http://localhost:4200/post

or The Below method page will blink also bundle will again requested to load. the above method is best

<a href="/post">Post</a>
Example : http://localhost:4200/post

2. Navigate programmatically

​Example : http://localhost:4200/post

3. Rounter Link Active current menu​

 <li routerLinkActive="active current"><a routerLink="/post">Post</a></li>​

4. Create Router Link with multiple parameters​

<a [routerLink]="['profile','ashok','kuamr']">Post</a>
 Example : http://localhost:4200/profile/ashok/kumar

5. Navigate with multiple parameters programmatically

Example : http://localhost:4200/profile/ashok/ad5081

6. Create Router Link with Query parameter​

<a routerLink="/follows" [queryParams]={page:1,id:2}>Follows</a>
Example : http://localhost:4200/follows?page=1&id=2

7. Navigate with Query parameter programmatically​

this.router.navigate(['/profile'],{queryParams:{id: "someId"}});
Example : http://localhost:4200/profile?id=someId

8. Navigate with multiple praameter and multiple query​

 this.router.navigate(['/profile','ashok','ad5081'],{queryParams:{id: "someId", id2: "anotherID"}});
 Example : http://localhost:4200/profile/ashok/ad5081?id=someId&id2=anotherID​

9.Set Default path in RouterModule​

Example : http://localhost:4200  redirect to FollowersComponent

10.Set Default path in RouterModule and redirect to particular url​

{path:'',redirectTo: 'pesonal', pathMatch: 'full'}
Example : http://localhost:4200  redirect to FollowersComponent

11. Set specific URL to specific component​

Example : http://localhost:4200/follows     //redirect to FollowersComponent

12. Specific URL with Two parameters rediect to specific component​

Example : http://localhost:4200/profile/ashok/ad5081 redirect to ProfileComponent

13. URL not found rediect to specific component​

Example : http://localhost:4200/url-not-found redirect to TestservicesComponent

14. Accessing Router Paremater​

constructor(private route:ActivatedRoute) { }

ngOnInit() {
params=>{ console.log(params.get('username'));
console.log(params.get('id')); }

Example : http://localhost:4200/profile/ashok/ad5081
Console : ashok
console : ad5081

15. Accessing Query parameter​

constructor(private route:ActivatedRoute) { } 

ngOnInit() {
    this.sub = this.route
      .subscribe(params => {
        // Defaults to 0 if no query param provided. = +params['page'] || 0;

   Example : http://localhost:4200/profile?page=1
   Console : 1


Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed