How To Pass Data In URL From One Component To Another In Angular

In this article, we will see ho we can pass data in URL from one component to another component. There are too many ways to pass data from one component to another, but here, we will implement it with the help of the NavigationExtras interface. This interface specifies a root URI to use for relative navigation.

For example, consider that you have a list of articles and on click, on any one article you want to view that article, which is another component, so for this scenario you can pass article id or title or URL pass as a query string and receive on view article component.

Let’s assume we have one component namely ‘list-articles’ which has all articles as table view and the last column is for the view that article. On click on that view button, we want to open that full article on another component namely ‘view-article’.

To do this, first, we need a button as view, on click of that button we will call our function which has logic to navigation.

<button class="btn btn-primary" (click)="navigateToArticle(article.Id)">View</button>

list-articles.component.ts file logic.

Import the following classes.

import { NavigationExtras, Router } from '@angular/router';

In the constructor method pass ‘Router’ as a parameter.

constructor(private router: Router) {}

Function to navigate which we are calling from a button click.

navigateToArticle(id) {
  let navigationExtras: NavigationExtras = {
    queryParams: {
      "articleId": id
    }
  };
  this.router.navigate(['/view-article'], navigationExtras);
}

view-article.component.ts file logic.

Import following class.

import { ActivatedRoute } from '@angular/router';

Declare variable inside a class.

private sub: any;

In the constructor method pass ‘ActivatedRoute’ as a parameter. ActivatedRoute Sets query parameters to the URL.

constructor(private route: ActivatedRoute) {}

Logic to read parameter from URL, you can write this logic anywhere like OnInit or AfterViewInit, etc.

this.sub = this.route.queryParams.subscribe(params => {
    let id = params["articleId"];
    if (id) {
      alert(id);
    }
  });

That’s it, you can pass as many as parameters in URL as per need.

ope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

You can find more relevant articles here.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories