AppDividend
Latest Code Tutorials

Angular RouterLink Example | Angular 10 RouterLink

0

RouterLink is an inbuilt Angular Directive that lets you link to specific routes in your app. In a SPA(single-page application), you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page.

As users need to perform application tasks, they need to move between the different views that you have defined. To implement navigation between different routes within your single-page app, use the Angular Router.

Angular RouterLink

RouterModule provides RouterLink directive in Angular. The RouterModule adds router directives and providers. RouterLink lets us link to the specific routes in our angular application.

Consider the following route configuration: [{ path: ‘customer/:id’, component: CustComponent }]. When linking to this customer/:id route, you use the RouterLink directive.

If there is a static link, you can use the directive as follows: <a routerLink=”/customer/21″>link to cust component</a>

If you use dynamic values to generate a link, you can pass the array of path segments, followed by the parameters for each segment.

For instance [‘/group’, groupId, ‘user’, userName, {full: true}] means that we want to generate a link to /group/21/user/billy;full=true.

Routing segments

The first segment name can be prepended with /. /, or . . /:

  1. If the first segment begins with /, the router will look up the route from the root of the app.
  2. Suppose the first segment begins with . /, or doesn’t start with a slash, the router will instead look in the children of the current activated route.
  3. And if the first segment begins with . . /, the router will go up one level.

Set Query Parameters in Angular

To set query parameters in Angular, use the following syntax.

<a [routerLink]="['/customer/jt']" [queryParams]="{purchase: true}">
  link to customer component
</a>

RouterLink will use these to generate this link: /customer/jt;purchase=true.

You can provide a state value to be persisted to the browser’s History.state property.

<a [routerLink]="['/customer/jt']" [state]="{transactionId: 123}">
  link to customer component
</a>

Method of RouterLink

The RouterLink provides one method called onClick().

The onClick() method does not accept a single parameter and returns a Boolean value.

Example of RouterLink directive

To create an Angular 10 project, you must upgrade Angular CLI.

To create a new Angular project, type the following command.

While creating a new project, please enable the routing by selecting y in the options.

ng new angularguard

You can name your project whatever you want.

Now, go inside the project folder and install Bootstrap CSS Framework.

npm install bootstrap --save

Register the CSS file inside the angular.json file.

"styles": [
       "src/styles.css",
       "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Now, create the following two new Angular components.

  1. HomeComponent
  2. DashboardComponent

Type the following commands to create it.

ng g c home --skipTests=true
ng g c dashboard --skipTests=true

After creating components, we will define the routes array that contains different objects.

So, write the following code inside the app-routing.module.ts file.

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { DashboardComponent } from './dashboard/dashboard.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent},
  { path: 'dashboard', component: DashboardComponent }
];

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

You can map the different routes to different components here and, finally, register all the routes using RouterModule.forRoot() function.

The Router-Outlet is the directive that’s provided by the angular router library where the router adds the component that gets matched based on the current browser’s URL.

In our example, let’s write <router-outlet> directive inside the app.component.html file. We will also add the navigation bar inside the app.component.html as well.

<nav class="navbar navbar-light navbar-expand-lg" style="background-color: #e3f2fd;">
  <div class="container">
    <a class="navbar-brand">AppDividend</a>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a class="nav-link">
            Home
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link">
            Dashboard
            </a>
          </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>

You can see that we have not written a routerLink directive inside the anchor tag.

To navigate from one route to another, we have to put the routerLink directive.

The routerLink directive takes a route path which we have already defined inside the routes array.

Let’s add the directive.

<!-- app.component.html -->

<nav class="navbar navbar-light navbar-expand-lg" style="background-color: #e3f2fd;">
  <div class="container">
    <a routerLink="/" class="navbar-brand" routerLinkActive="active" >AppDividend</a>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
        <ng-container>
          <li class="nav-item">
            <a routerLink = "home" class="nav-link">
            Home
            </a>
          </li>
          <li class="nav-item">
            <a routerLink = "dashboard" class="nav-link">
            Dashboard
            </a>
          </li>
         </ng-container>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>

Okay, so now we have two views, and we can navigate between those views using routerLink.

We can also write the routerLink directive like this.

<ng-container>
      <li class="nav-item">
         <a [routerLink] = "['/home']" class="nav-link">
            Home
         </a>
      </li>
      <li class="nav-item">
         <a [routerLink] = "['/dashboard']" class="nav-link">
            Dashboard
         </a>
      </li>
</ng-container>

Pass Query Parameters in Angular

To pass the query parameters, you can write the anchor tag like the following.

<ng-container>
       <li class="nav-item">
          <a [routerLink] = "['/home']" [queryParams] = "{success: true}" class="nav-link">
            Home
          </a>
        </li>
        <li class="nav-item">
          <a [routerLink] = "['/dashboard']" class="nav-link">
            Dashboard
          </a>
        </li>
</ng-container>

Start the dev server by the following command.

ng serve -o

It will open up the browser with http://localhost:4200 URL.

Click on the home link, and you will see the following URL.

http://localhost:4200/home?success=true

That is it. We have successfully passed the query parameters to the HomeComponent.

We can capture the parameter and put some conditions based on that parameter values. For example, display the notification like a bootstrap alert box on success or failure.

Write the following code inside the home.component.ts file.

// home.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  notify: string;
  constructor(private router: Router, private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      if (params.success === 'true') {
        this.notify = 'You have passed data';
      }
    });
  }
}

In this code, we have used the queryParams.subscribe() function to get the query parameters passed to the current URL. 

Based on the condition, we are setting the notify message.

Now, write the following code inside the home.component.html file.

<!-- home.component.html -->

<div *ngIf="notify" class="alert alert-success">
    {{ notify }}
</div>
<p>home works!</p>

Okay, now see the output in the browser.

 

Angular RouterLink Example

Now, if you remove the query parameters from the URL and just hit this URL: http://localhost:4200/home, then you will not get any notification message.

Conclusion

In this example, we have seen how to use routerLink directive in navigation and how to pass query parameters and capture the queryParams using ActivatedRoute.

That’s it for the Angular 10 RouterLink example.

See also

Angular router navigate

Angular route guard

Angular 10 Tutorial

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.