Router - AngularBuildUp/angular-microworkshops-authorization GitHub Wiki
An Angular application is a tree of components. The router cares about application components and their arrangments. Component arrangements can be called router states and a state defines what is visible on the screen.
Router configuration is a tree with every node representing a route. A router state is a subtree of the configuration tree. Router's primary job is to manage navigation between states which includes updating the component tree. Navigation is the act of transitioning from one router state to another
The angular router takes a URL then does the following:
- Applying redirects
- Recognize router states
- Running guards and resolving data
- Activating all the needed components
- Managing navigation
Flow
Routing directives
the directives (ROUTER_DIRECTIVES) tells the template what routerLink and are
<a [routerLink]=["Dashboard"]>…</a>
<a [routerLink]=["Vehicles"]>…</a>
<router-outlet></router-outlet>
The routerLink
directive takes an array because this way we can define additional route paths and parameters.
In the <router-outlet>
we put the content of the route displaying.
Adding routing and navigation links
<a [routerLink]=["Vehicle", {id: vehicle.id}]>..</a>
We define routing parameters to routerLink
directive by passing an object to its value, populating the properties the router wants.
To get the parameter from the component we call (route) we need to inject the RouteParams
to the component
with the get
method of RouteParams
we get the route parameter
Example
var id = this.routeParams.get("id");
To navigate programmatically, use the navigate
method of Router
.
import { Router } from '@angular/router';
constructor(private router: Route) {}
this.router.navigate(['/Vehicles']);
You can use just single strings to concatenate routes
this.router.navigate(["let", "me", "share", "some", "secret"]);
// this resolve to /let/me/share/some/secret
You can also use the extras
parameter to add extra in the URL, like a query string. The following is including a query string type
with value of 'truck'
this.router.navigate(['/vehicles'], { queryParams: { type: 'truck' } });