In this tutorial we is going to learn what to navigate programmatically (or imperatively) by using the Router API. We is going to learn how to use the function Navigatebyurl to navigate using a manually constructed string, but we are AL So-going to learn-trigger route navigation by using the Navigate API method, which takes an array or arguments and A Parameters object.
We is going to learn how to do both absolute and relative route navigation using the Navigate API, and we is going to in Troduce the notion of activated route.
In our heroscomponent, we add input box and when you enter the number, it'll goes to fetch the hero:
Heros.routes.ts:
Import {heroscomponent} from "./heros.component"; import {routermodule} from "@angular/router"; import {herocomponent} from "./hero/hero.component";ConstRoutes =[{path:"', component:heroscomponent}, {path:': ID', Component:herocomponent},];exportdefaultRoutermodule.forchild (routes)
Heros.component.html:
Search Index:<inputtype= "text"placeholder= "Search"(Keyup.enter)= "Getherobyindex (inpref.value)"#inpRef><ul> <Li*ngfor= "Let Hero of Heros | async"> <a[Routerlink]= "Hero.id"routerlinkactive= "Active"[Routerlinkactiveoptions]= "{exact:true}">{{Hero.name}}</a> </Li> <!--we can also do [routerlink]= "['/heros ', hero.id]", this would point to "HEROS/1"; If you do: [routerlink]= "[' heros ', hero.id]", this would point to "HEROS/HEROS/1" Since we is already in Heros MoD Ule We just need to does [routerlink]= "Hero.id", point to "HEROS/1 " -</ul>
Heros.component.ts:
Import {Component, OnInit} from '@angular/core'; import {Starwarsservice} from "./heros.service"; import {Observable} from "RXJS"; import {Router, activatedroute} from "@angular/router"; @Component ({selector:'App-heros', Templateurl:'./heros.component.html', Styleurls: ['./heros.component.css']}) exportclassHeroscomponent implements OnInit {heros:observable<any>; Constructor (PrivateStarwasservice:starwarsservice,PrivateRouter:router,PrivateRoute:activatedroute) {} ngoninit () { This. heros = This. Starwasservice.getpeople (); } getherobyindex (i) {//this.router.navigateByUrl ('/heros/${i} '); //this.router.navigate ([' heros ', I]); This. router.navigate ([i], {relativeto: This. Route}) }}
If you type ' enter ', would call Getherobyindex function, there is three ways to Nav to a router programmtically.
1. Navigatebyurl:it accepts an router URL.
2. Navigate:first param is an array, absolute path: [' contacts ', id]--CONTACTS/1
3. Recommend:relative Path:
' This.route ': Point-to-the-current router.
[i]: the relative path to the current router.
Github
[Angular2 Router] Programmatic Router Navigation via the Router api-relative and Absolute Router Navigation