Angular RouterLink Example

By Arvind Rai, March 07, 2024
On this page we will learn to use RouterLink in our Angular routing application.
1. To create router links, Angular provides following directives.
RouterLink : Creates an HTML element as link to navigate to a specified route.
RouterLinkActive : Tracks whether the link is currently active or not and allows us to add CSS class when link is active.
2. The route when navigated by RouterLink, components open in one or more <router-outlet>.
3. We can pass query parameters using queryParams property and fragment using fragment property.
4. RouterLink is used with HTML elements such as <a> and <button> in HTML template.
5. To use RouterLink directive, we need to import RouterModule in our application.
routerLink is the selector of RouterLink directive. It is applied to HTML elements such as <a> and <button>. When applied to an element, routerLink makes that element a link to navigate to a specified route. In the navigation, one or more components are opened in one or more <router-outlet> .
Ex-1
<a routerLink="/customers/items">Customers</a> 
On the click on above link, application will navigate to /customers/items URL.
Ex-2
<a [routerLink]="['customers', 10, 'items', 101]">Customers</a> 
When user clicks on the link, application will navigate to below URL.
/customers/10/items/101 
routerLink accepts an array of URL segments using which we can create URL dynamically. We can pass URL segments followed by path parameters to create URL.

2. routerLinkActive

routerLinkActive is the selector of RouterLinkActive directive. It is used with routerLink directive. In an element, routerLinkActive tracks whether the linked route is currently active or not. It tracks currently active route by changing elements appearance using one or more specified CSS classes.
routerLinkActive is used as following.
1.
<a routerLink="/emp/101" routerLinkActive="active">Ram</a> 
active is our CSS class that will be applied on link 'Ram' when the route /emp/101 is navigated successfully.
2. We can specify more than one CSS classes to routerLinkActive in following ways.
<a routerLink="/emp/101" routerLinkActive="class1 class2">Ram</a>

<a routerLink="/emp/101" [routerLinkActive]="['class1', 'class2']">Ram</a> 
Find the properties of RouterLink directive and their usages.
1. queryParams sets query parameters.
<a routerLink="/company/emp" 
[queryParams]="{empId: 101, name: 'Mohit'}"
routerLinkActive="active">link</a> 
Created URL:
/company/emp?empId=101&name=Mohit 
2. fragment sets hash fragment.
<a routerLink="/book" 
[queryParams]="{page: 100}"
[fragment]="'top'"
routerLinkActive="active">link</a> 
Created URL:
/book?page=100#top 
3. queryParamsHandling decides how to handle query parameters for the next navigation. Its values are preserve and merge.
<a routerLink="/userdetail" 
  [queryParams]="{id: 101, city: 'Varanasi'}"
  queryParamsHandling="merge">link</a> 
When we use merge, the current and new query parameters are merged.
When we use preserve, only current parameters are preserved in the next navigation and new parameters are discarded.
4. relativeTo specifies a root URI to enable relative navigation. Assign the instance of ActivatedRoute to relativeTo.
TS code:
constructor(private route: ActivatedRoute){} 
HTML code:
<a [routerLink]="['book', 101]" [relativeTo]="route" >link</a> 
5. state accepts the state defined by us to pass to any navigation. The state values are persisted to History.state property.
<a [routerLink]="['user', 51]" [state]="{appId: 221}" >link</a> 
6. preserveFragment preserves the current URL fragment to next navigation. Its values are boolean. Default value is false.
<a [routerLink]="['/book/java']" fragment="bottom" preserveFragment="true" >link</a>< 
7. skipLocationChange is a boolean property. When its value is true, URL will not change in the browser and navigation happens without pushing new state into history.
<a [routerLink]="['/user/50']" skipLocationChange="true">link</a> 
8. replaceUrl is a boolean property. When its value is true, it navigates replacing the current state in the history.
<a [routerLink]="['/team/emp']" replaceUrl="true" >link</a> 

4. Properties of routerLinkActive

Find the properties of routerLinkActive directive and their usages.
1. routerLinkActive property is used to check if link is active or not using template variable. We need to assign routerLinkActive to template variable and then call isActive on that variable.
<a [routerLink]="['/writer/10']"  routerLinkActive #routerLnkAct="routerLinkActive">
			{{routerLnkAct.isActive}} link </a> 
2. routerLinkActiveOptions configures when the router link should be active. For example, add CSS classes only when URL matches exactly. Find code snippet to use routerLinkActiveOptions with exact boolean property. The default value of exact is false.
<a [routerLink]="['/books/10']" routerLinkActive="active-class" 
	  [routerLinkActiveOptions]="{exact:true}" >link</a> 
When the value of exact is true, CSS class will be added to link only when current route is exactly /books/10 but for the route /books/10/15 , CSS class will not be added.
For UrlTree, assign IsActiveMatchOptions instance to routerLinkActiveOptions.
3. isActiveChange is an output property that notifies each time the link is active or inactive. It emits true when link is active and emits false when link is inactive.
TS code:
onWriterLinkActive(activeStatus: boolean) {
  console.log(activeStatus);
} 
HTML code:
<a [routerLink]="['/writers/10']"  routerLinkActive="active" 
	(isActiveChange)="onWriterLinkActive($event)" >Writer</a> 

5. Creating Tabs

Find an example to create tabs using routerLink directive.
<nav class = "menu-items">
  <ul>
	<li><a routerLink="/product/" routerLinkActive="active">Products</a></li>
	<li><a routerLink="/customers/" routerLinkActive="active">Customers</a></li>
	<li><a routerLink="/help/" routerLinkActive="active">Help</a></li>
  </ul> 
</nav> 
Here I have three tabs that will open URL assigned to routerLink. I have created a CSS class with name active.
.active{
   background-color: #4CAF50;
} 
When a tab is clicked, the active class is added to that <a> element.
Tabs can also be created using <button> element.
<li><button routerLink="/product/" routerLinkActive="active">Products</button></li> 
Find the output screen.
Angular RouterLink Example

6. References

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us