Angular Route

From Logic Wiki
Jump to: navigation, search

app module

in app.module.ts file

import { RouterModule } from '@angular/router'
@NgModule({...
  imports:[RouterModule.forRoot([
       {path:, component: HomeComponent},
       {path:'followers', component:FollowersComponent },
       {path:'profile/:username', component:ProfileComponent },
       {path:'**', component:NotFoundComponent} 
       ])
  ]...

Router Outlet

in main page add

<router-outlet></router-outlet>

nav routes should go under this tag

RouterLink

<a routerLink="/followers">Followers</a>

or

<a [routerLink]="['followers', follower.id]">follower</a>

RouterLinkActive

to highlight active route we use RouterLinkActive. it uses the css class if link is active

  • <a routerLink="/followers">Followers</a>
  • paramMap - Parameters in route

    in profile component

    import {ActivatedRoute } from '@angular/router';
    

    in constructor

    constructor(private route: ActivatedRoute){}
    

    in ngOnInit()

    ngOnInit(){
       this.route.paramMap
           .subscribe(params => {
               console.log(params);
               let username = params.get('username');
          });
    }
    

    Routes with multiple parameters

    in app module under imports

    {path:'profile/:id/:username', component:ProfileComponent },
    

    and in Router Link

    <a[routerLink]="['/followers', follower.id, follower.login]">
    

    Optional parameters in route

    sending

     <a routerLink="/followers" [queryParams]="{page:1, order:'name'}">Followers</a>
    

    receiving

    ngOnInit(){
       this.route.queryParamMap
           .subscribe(params => {
               console.log(params);
               let username = params.get('username');
          });
    

    Getting both parameters / Subscribing multiple components

    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/combineLatest'; // static method in observable
    

    in ngOnInit()

    ngOnInit(){
     Observable.combineLatest([
       this.route.paramMap,
       this.route.queryParamMap
     ])
      .subscribe(combined => {
         let id = combined[0].get('id');    // for paramMap
         let page = combined[1].get('page');   // for queryParamMap
       });