The router directives – RouterOutlet, RouterLink, and RouterLinkActive

We already mentioned in the Adding support for the Angular router section, that to set up a router there were some essential basic steps to make routing work. Let's remind ourselves of what they were:

  • Define a routes list
  • Initialize the Route module
  • Add a viewport

For the intents and purposes of this practical example, we have done the top two items, what remains is to add the viewport. A directive handles the viewport for Angular; it is called the RouterOutlet and just needs to be placed in the template for the component that sets up routing. So essentially, by opening up app.component.html and adding <router-outlet></router-outlet>, we sort out the last bullet item on our list.

There is a lot more to routing, of course. One interesting thing, which is expected of every router, is the ability to generate clickable links given a defined route. The routerLink directive handles that for us and is used in the following way:

<a routerLink="/" routerLinkActive="active">Home</a>

The routerLink points to the route path, note the leading slash. This will look up which route item is defined in our routes list that corresponds to the route path /. After some investigation in our code, we find a route item that looks like the following:

[{
path : '',
component : HomeComponent
}]

Take extra notice here that when defining the route; we should not have a leading slash, but when creating a link with said route item and using the routerLink directive, we should have a trailing slash. 

This has produced the following element:

<a _ngcontent-c0="" routerlink="/" routerlinkactive="active" ng-reflect-router-link="/" ng-reflect-router-link-active="active" href="/" class="active">Home</a>

That looks interesting, the key take away is that href is set to / and the class has been set to active.

The last bit was interesting, why would the class be set to active? That's what the routerLinkActive="active" does for us. It investigates whether the current route we are on corresponds to the routerLink element we are currently on. If so, it gets awarded the active CSS class. Consider the following markup:

<a routerLink="/" routerLinkActive="active" >Home</a>
<a routerLink="/tasks"routerLinkActive="active" >Tasks</a>
<a routerLink="/timer"routerLinkActive="active" >Timer</a>

Only one of the elements will get the active class set. If the browser URL points to /tasks, it will be the second item, instead of the first. The fact that the active class is being added gives you, as developer, the opportunity to style the active menu element, because a menu is what we are creating by defining a list of links, such as the preceding code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset