Tuesday, August 11, 2020

Setting and Fetching Route Parameters in Angular

In this post we’ll see how to set and fetch route parameters in Angular routing.

Route parameters in Angular

In our web apps we do need to navigate to a specific resource. For example we want the details of a specific account number then we can navigate to that account number by using URL- /account/A1001 or to another account by using URL- /account/A1002.

It is not practical to hardcode the path segment for each account number, you will use a route parameter instead that acts as a placeholder. Value passed for the placeholder becomes the value of the route parameter.

In a route that takes a parameter, route parameter is specified by prefixing it with a colon. So the route definition will be like- /route/:routeparam

You can pass more than one route parameter too- /route/:param1/:param2/:param3

Route parameters in Angular example

In the example we show user a list of account numbers then the details of the account number that is clicked are showed using a separate component. In this scenario you can pass the clicked account number as route parameter.

Here are the route definitions for the routes. Here AccountsComponent displays all the account numbers for a user and AccountComponent shows details for the selected account number.

const routes: Routes = [
                        {path: 'home', component: HomeComponent},                  
                        {path: 'account', component: AccountsComponent},
                        {path: 'account/:acctno', component: AccountComponent},
                        {path: 'service', component: ServiceComponent},
                        {path: '', redirectTo:'/home', pathMatch: 'full'}                  
];

As you can see there is a route with route parameter- {path: 'account/:acctno', component: AccountComponent}

Code for menu and adding link for routes is done in the app.component.html template itself for this example.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/home">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

Components

We’ll concentrate here on AccountsComponent and AccountComponent for the code of other components please refer- Angular Routing Concepts With Example.

AccountsComponent (accounts.component.ts)

In the component we have an array to show account numbers and a method onAccountClick() to navigate programmatically to a route.

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accounts = ['A1001', 'A1002'];
  constructor(private router: Router, private route: ActivatedRoute) {}
  onAccountClick(account: string){
    this.router.navigate([account], {relativeTo:this.route});
  }
}

Two classes Router class and ActivatedRoute class are injected into the component.

  • Router class has navigate() method using which we navigate to a URL dynamically.
  • ActivatedRoute class provides access to information about the current route.

This line of code instructs Angular to navigate to the path which is relative to current route (localhost:4200/account in our example) and adds the value of account to it making it a route in this format- http://localhost:4200/account/ACCOUNT_NUMBER

this.router.navigate([account], {relativeTo:this.route});

Since we already have a route definition with a route parameter {path: 'account/:acctno', component: AccountComponent} which matches any route in this format http://localhost:4200/account/ACCOUNT_NUMBER so that’s how AccountComponent gets called.

accounts.component.html

<div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <div class="list-group">
      <a [routerLink]="" 
        (click)="onAccountClick(account)" 
        class="list-group-item"   
        *ngFor="let account of accounts">
        {{ account }}
      </a>
    </div>
  </div>
</div>

AccountComponent (account.component.ts)

In this component we simulate a scenario where we have details for all the account numbers and we have to get the details for the account number which is sent as route parameter.

To extract the parameter route.params observable is used and we subscribe to it so that when ever there is a change the parameter is extracted into a acctNo variable. Using the fetched account number we find the related object in the array using the find() method.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent implements OnInit{
  acctNo: string;
  account: {accountnumber: string, type: string, balance: number};
  constructor(private route: ActivatedRoute){ }
  accountDetails = [
    {
      accountnumber: 'A1001',
      type: 'Saving', 
      balance: 22000
    },
    {
      accountnumber: 'A1002',
      type: 'Checking',
      balance: 1000
    }
  ];

  ngOnInit() {
    //this.acctNo = this.route.snapshot.params['acctno'];
    this.route.params.subscribe((params: Params)=> this.acctNo = params['acctno']);
    this.account = this.accountDetails.find(e=>e.accountnumber === this.acctNo);
  }
}

Note that you can also extract parameter from the route using the current snapshot of the route. But route.params observable is preferred.

this.acctNo = this.route.snapshot.params['acctno'];

account.component.html

<h2>Account Details</h2>
<div class="row">
  <div class="col-xs-6">
    <label>Account Number: </label> {{ account.accountnumber }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Account Type: </label> {{ account.type }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Balance: </label> {{account.balance}}
  </div>
</div>

Accounts Component

Account Component

That's all for this topic Setting and Fetching Route Parameters in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Navigate to a Route Programmatically in Angular
  3. Using RouterLinkActiveOptions to Fix Link Highlighted Problem
  4. Highlight Currently Selected Menu Item Angular Routing Example
  5. Angular Custom Property Binding Using @Input Decorator

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular ngSwitch Directive With Examples
  3. Angular @Input and @Output Example
  4. How to Add Bootstrap to Angular Application
  5. PriorityBlockingQueue in Java Concurrency
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Predefined Mapper And Reducer Classes in Hadoop
  8. Passing Arguments to getBean() Method in Spring

Monday, August 10, 2020

Navigate to a Route Programmatically in Angular

In this post we’ll see how to navigate to a route programmatically or dynamically using router.navigate() or router.navigateByUrl() methods in Angular.

Navigating to a route dynamically Angular example

You may have a scenario where you would like to navigate to a route based on an event like click of a button, clicking a link. Here is a simple example which uses router.navigate() method to navigate to a route on a click of a button.

There is a menu as shown below and you have to show the corresponding component on click of the menu option.

1. Creating routing module

We’ll create a separate routing file app-routing.module.ts with routes array to define route paths and component they map to.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccountsComponent } from './accounts/accounts.component';
import { AccountComponent } from './accounts/account/account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';


const routes: Routes = [
                        {path: '', component: HomeComponent},                  
                        {path: 'account', component: AccountsComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2. Import the AppRoutingModule into AppModule (app.module.ts) and add it to the imports array.

import { AppRoutingModule } from './app-routing.module';
imports: [
  BrowserModule,
  AppRoutingModule
],

3. Adding the configured routes to the application.

Code for menu and adding link for routes is done in the app.component.html template itself for this example.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
          <a class="nav-link" routerLink="/">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

Creating components

Now as per our route mapping there are 3 components HomeComponent, AccountsComponent and ServiceComponent.

Home Component (home.component.ts)

From the home page you want to provide a button to take to AccountsComponent. That route navigation will be done programmatically.

import { OnInit, Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  userId = 'UID0023';
  constructor(private router: Router) { }

  ngOnInit() {
  }

  navigateToAccount(){
    this.router.navigate(['/account']);
  }
}

To use Router.navigate method first you need to inject the Router class in your component. That is done in the constructor.

In the method navigateToAccount(), router.navigate() method is used to navigate to a route. In navigate method you pass an array of elements that are joined together to create a path. For example router.navigate(‘account’, 1) resolves to a path /account/1.

If you want to use router.navigateByUrl() method then you can also use this.router.navigateByUrl('/account'); With router.navigateByUrl() you can pass an absolute path, for example router.navigateByUrl(‘/account/1’).

Note that in this example path passed in this.router.navigate(['/account']); is an absolute path (not relative).

home.component.html

<h4>Welcome to XYZ Bank</h4>
<p>{{ userId }} logged in.</p>
<div>
    <button type="button" class="btn btn-primary" (click)="navigateToAccount()">My Accounts</button>
</div>

Account Component (account.component.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accounts = ['A1001', 'A1002'];
}

accounts.component.html

<div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <!-- [routerLink]="" 
    (click)="onAccountClick(account)" -->
    <div class="list-group">
      <a class="list-group-item"   
        *ngFor="let account of accounts">
        {{ account }}
      </a>
    </div>
  </div>
</div>

Service Component (service.component.ts)

import { Component } from "@angular/core";

@Component({
  selector: 'app-service',
  templateUrl:'./service.component.html'
})
export class ServiceComponent{
  services = [
    'Deposit Money',
    'Open FD',
    'Mail Customer Care'
  ]; 
}

service.component.html

<h2>Services Offered</h2>
<div class="row">
  <div class="col-xs-12 col-sm-6">
    <div class="list-group">
      <a
        href="#"
        class="list-group-item"
        *ngFor="let service of services">
        {{ service }}
      </a>
    </div>
  </div>
</div>

Add these components in the declarations array of the AppModule before running the example.

You will have a button in the HomeComponent which navigates you to the AccountsComponent when clicked.

Navigate to a Route Programmatically in Angular

Dynamic route Navigation using relative path in Angular

In the previous example we used absolute path with navigate() method but you can also pass a relative path but in that case you need to specify path is relative to which existing path.

Let’s change the previous example to have one more component AccountComponent that shows the details for the account selected in AccountsComponent.

For that routes array will have to be changed in the following way-

const routes: Routes = [
                        {path: '', component: HomeComponent},                  
                        {path: 'account', component: AccountsComponent},
                        {path: 'account/:acctno', component: AccountComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

As you can see a new route definition is added- {path: 'account/:acctno', component: AccountComponent}, here :acctno is a placeholder that matches any account number so URL like account/A001 or account/A002 both will match this route.

Accounts component is also changed-

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accounts = ['A1001', 'A1002'];
  constructor(private router: Router, private route: ActivatedRoute) {}
  onAccountClick(account: string){
    this.router.navigate([account], {relativeTo:this.route});
  }
}

Along with Router class now ActivatedRoute class is also injected into the component. ActivatedRoute class provides access to information about a route associated with a component that is loaded in router outlet.

In router.navigate() method you can also pass a second argument of type navigationExtras. One of the NavigationExtras is relativeTo which specifies a root URI to use for relative navigation.

In the example navigate method is now like this-

this.router.navigate([account], {relativeTo:this.route});

Here this.route specifies the route associated with the component, in our case it will be /account so relative path is http://localhost:4200/account

[account] specifies the account number that is clicked which can be either A1001 or A1002. Thus the navigation route is derived as either http://localhost:4200/account/A1001 or http://localhost:4200/account/A1002 which matches the route definition {path: 'account/:acctno', component: AccountComponent}.

AccountComponent (account.component.ts)

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent implements OnInit{
  acctNo: string;
  account: {accountnumber: string, type: string, balance: number};
  constructor(private route: ActivatedRoute){ }
  accountDetails = [
    {
      accountnumber: 'A1001',
      type: 'Saving', 
      balance: 22000
    },
    {
      accountnumber: 'A1002',
      type: 'Checking',
      balance: 1000
    }
  ];

  ngOnInit() {
    this.acctNo = this.route.snapshot.params['acctno'];
    this.account = this.accountDetails.find(e=>e.accountnumber === this.acctNo);
  }
}

Here we have defined an account type- account: {accountnumber: string, type: string, balance: number};

There is also an array with values for account.

In ngOnInit() using the passed account number we find the related object in the array using the find() method.

Account number parameter is extracted from the route using the current snapshot of the route.

this.route.snapshot.params['acctno'];

account.component.html

<h2>Account Details</h2>
<div class="row">
  <div class="col-xs-6">
    <label>Account Number: </label> {{ account.accountnumber }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Account Type: </label> {{ account.type }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Balance: </label> {{account.balance}}
  </div>
</div>

Accounts Component

Account Component

navigating route dynamically angular

That's all for this topic Navigate to a Route Programmatically in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Highlight Currently Selected Menu Item Angular Routing Example
  3. Angular Two-Way Data Binding With Examples
  4. Angular Custom Property Binding Using @Input Decorator
  5. Injector Hierarchy and Service Instances in Angular

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular @Input and @Output Example
  3. Angular - Call One Service From Another
  4. Creating New Component in Angular
  5. Pre-defined Functional Interfaces in Java
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Writing a File Asynchronously Java Program
  8. Passing Arguments to getBean() Method in Spring

Saturday, August 8, 2020

Switch Expressions in Java 12

In Java 12 Switch statement has been extended to be used as either a statement or an expression. In this article we’ll see with some examples how to use this new feature switch expressions in Java.


Java Switch expressions

A new form of switch label, written "case L ->" has been added in Java 12 that allows the code to the right of the label to execute only if the label is matched.

We’ll try to understand this switch expression with an example, initially let’s use traditional switch statement to write a conditional switch-case branch and then use switch expression to see how it simplifies it.

For example if you want to display the quarter, passed month falls into then you can group three case statements where break statement is used with only the last one in the group.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 4;  
  switch(month){
   case 1:    
   case 2:    
   case 3: System.out.println("Quarter 1"); 
     break;
   
   case 4:   
   case 5:     
   case 6: System.out.println("Quarter 2"); 
     break;
   
   case 7:   
   case 8:  
   case 9: System.out.println("Quarter 3"); 
     break;
   
   case 10:     
   case 11:   
   case 12: System.out.println("Quarter 4"); 
      break;
   
   default: System.out.println("Invalid month value passed");
  }
 }
}

Consider some of the pain areas here-

  1. Even if multiple cases have the same end value still you need to write them in the separate lines.
  2. Use of many break statements make it unnecessarily verbose.
  3. Missing a break statement results in an accidental fall-through.

Now let’s write the same example using switch expressions.

public class SwitchCaseDemo {

  public static void main(String[] args) {
    int month = 4;        
    switch(month){
      case 1, 2, 3 -> System.out.println("Quarter 1");         

      case 4, 5, 6 -> System.out.println("Quarter 2");     
  
      case 7, 8, 9 -> System.out.println("Quarter 3");             
       
      case 10, 11, 12 -> System.out.println("Quarter 4");              
      
      default -> System.out.println("Invalid month value passed");
    }
  }
}

Note the changes here-

  1. Multiple case labels can be grouped together now.
  2. Break statement is not required any more. If a label is matched, then only the expression or statement to the right of an arrow label is executed; there is no fall through.
  3. This new switch form uses the lambda-style syntax introduced in Java 8 consisting of the arrow between the label and the code that returns a value.

Note that to use switch expressions feature make sure you have JDK 12 installed. To enable this feature, you’ll need to use the flags --enable-preview and --release 12 when you compile your code.

javac --enable-preview --release 12 SwitchCaseDemo.java

To run the generated class file, you’ll need to pass the --enable-preview flag to the Java launcher.

java --enable-preview SwitchCaseDemo

From Java 12 you can use colon syntax (:) too with multiple case labels but in that case break statement has to be used to avoid fall-through.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 4;  
  switch(month){
   case 1, 2, 3 : System.out.println("Quarter 1"); 
         break;

   case 4, 5, 6 : System.out.println("Quarter 2");  
       break;
   case 7, 8, 9 : System.out.println("Quarter 3");    
       break;
   case 10, 11, 12 : System.out.println("Quarter 4");     
       break;
   default : System.out.println("Invalid month value passed");
  }
 }
}

Why is it called Switch expression

Now the more pertinent question is why this new feature is called switch expression. As you must be knowing; Statements are essentially “actions” that have to be executed. Expressions, however, are “requests” that produce a value. Same difference applies to switch statement and switch expressions too.

Here is an example showing returning a value from a traditional switch statement.

public class SwitchCaseDemo {
 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  String message = "No event to log";
  switch (event) {
    case "Start":
      message = "User started the event";
      break;
    case "Stop":
      message = "User stopped the event";
      break;
  }
  return message;
 }
}

Output

User started the event

Same thing with Java Switch expressions. Since expression itself produces a value so it can be assigned to a variable directly.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  var msg = switch (event) {
    case "Start" ->  "User started the event";
    case "Stop" -> "User stopped the event";
    default -> "No event to log";
  };
  return msg;
 }
}

Output

User started the event

If you want to use colon syntax then you can assign the value directly after break.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  var msg = switch (event) {
    case "Start" : break  "User started the event";
    case "Stop" : break "User stopped the event";
    default : break "No event to log";
  };
  return msg;
 }
}

Writing statement blocks

If you need to have multiple statements with in a case you can use a statement block enclosed in curly braces.

public class SwitchCaseDemo {

  public static void main(String[] args) {
    int month = 4;        
    var value =switch(month){
      case 1, 2, 3 ->{
        System.out.println("Quarter 1");     
        break "Quarter 1";
      }
      case 4, 5, 6 -> {
        System.out.println("Quarter 2"); 
        break "Quarter 2";
      }
          
      case 7, 8, 9 ->{
        System.out.println("Quarter 3");     
        break "Quarter 3";
      }
               
      case 10, 11, 12 -> {
        System.out.println("Quarter 4");  
        break "Quarter 4";            
      }
              
      default -> {
        System.out.println("Invalid month value passed");
        break "Invalid month value";
      }
    };
    System.out.println("Value- " + value);
  }
}

That's all for this topic Switch Expressions in Java 12. If you have any doubt or any suggestions to make please drop a comment.Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. break Statement in Java
  2. Type Wrapper Classes in Java
  3. Ternary Operator in Java
  4. Type Casting in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Private Methods in Java Interface
  2. Multi-Catch Statement in Java Exception Handling
  3. Creating a Thread in Java
  4. How HashMap Works Internally in Java
  5. Byte Streams in Java IO
  6. Check if Given String or Number is a Palindrome - Java Program
  7. Spring Boot Hello World Web Application Example
  8. Connection Pooling With Apache DBCP Spring Example

Friday, August 7, 2020

Using RouterLinkActiveOptions to Fix Link Highlighted Problem

In the post Highlight Currently Selected Menu Item Angular Routing Example we saw how you can highlight the selected menu option but there may be one problem with that, menu option configured with root path route always remain highlighted. In this post we’ll see how to fix the problem of root path route always remaining highlighted in Angular using routerLinkActiveOptions.

Link remaining highlighted problem

If you have configured your routes arrays something like as given below-

const routes: Routes = [
                        {path: '', component: HomeComponent},                  
                        {path: 'account', component: AccountComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

And the routeLink as given here-

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
    <div class="row">
      <div class="col-md-12">
        <router-outlet></router-outlet>
      </div>
    </div>
</div> 

Then you will see the problem of link associated with the root ("/") always remain highlighted.

Using routerLinkActiveOptions in Angular

You can see in the image even if Services menu link is clicked, ‘Home’ remains highlighted.

This problem occurs because Angular considers root path segment to be the part of all the paths. Even if path is either http://localhost:4200/service or http://localhost:4200/account, root path segment “/” is always there. That is the reason the Link associated with empty path (“/”) is always highlighted.

Using routerLinkActiveOptions

In order to solve this problem using routerLinkActiveOptions. With routerLinkActiveOptions you can pass a javascript object {exact:true} to direct Angular to make link active only when exact path matches.

<li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
  <a class="nav-link" routerLink="/">Home</a>
</li>

With this configuration change ‘Home’ menu will only be highlighted when it is selected, as soon as you move away from this option it won’t remain highlighted anymore.

That's all for this topic Using RouterLinkActiveOptions to Fix Link Highlighted Problem. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Routing Concepts With Example
  2. Path Redirection in Angular Routing
  3. Angular Two-Way Data Binding With Examples
  4. Injector Hierarchy and Service Instances in Angular
  5. Angular Disable Button Example

You may also like-

  1. Angular ngClass Directive With Examples
  2. Angular Custom Event Binding Using @Output Decorator
  3. How to Add Bootstrap to Angular Application
  4. Angular - Call One Service From Another
  5. What is In-place Algorithm
  6. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  7. Switch Expressions in Java 12
  8. Python Exception Handling Tutorial

Thursday, August 6, 2020

Highlight Currently Selected Menu Item Angular Routing Example

In this article we’ll see how to highlight the currently selected menu item when using Angular routing and routerLink.

Note that Angular example shown here uses Angular 9 and Bootstrap 4.

RouterLink Directive in Angular

Angular RouterLink directive tracks whether the linked route of an element is currently active, it allows you to specify one or more CSS classes to add to the element when the linked route is active.

You can assign a CSS class as given below-

routerLinkActive="CSS_CLASS"
You can specify more than one CSS class using a space-separated string or an array.
routerLinkActive="CSS_CLASS1 CSS_CLASS2"

or

[routerLinkActive]="['CSS_CLASS1', 'CSS_CLASS2']"

Highlight currently selected menu item – Angular + Bootstrap example

In Bootstrap framework there is a CSS class active that can be used with routerLinkActive for the purpose of highlighting the selected menu item. Here is an example menu code.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/home">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

That's all for this topic Highlight Currently Selected Menu Item Angular Routing Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Angular Two-Way Data Binding With Examples
  3. Angular Custom Property Binding Using @Input Decorator
  4. Angular Application Bootstrap Process
  5. Injector Hierarchy and Service Instances in Angular

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular @Input and @Output Example
  3. Angular - Call One Service From Another
  4. Creating New Component in Angular
  5. Pre-defined Functional Interfaces in Java
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Writing a File Asynchronously Java Program
  8. Passing Arguments to getBean() Method in Spring