How To Pass Data To Route In Angular

How To Pass Data To Route In Angular

In this article, we will learn how to pass data to route in angular. We can pass data to the route using Angular. The route information can be static or dynamic. The static data is stored in the Angular route data property, which allows you to store any data related to this route. The historical state object can be used to pass dynamic data (or an object). The dynamic data from the historical state object can then be retrieved by the Routed Component.

Various ways of passing route data

Angular can provide data to Route in a variety of ways.

  1. Using URL or Route Parameter
  2. The Optional Parameter or Query Strings
  3. Using URL Fragment
  4. Static data using the data property
  5. Dynamic data using the state object

Passing static data to a route

At the time of route definition, we can configure the static data. The Angular route data property of the route is used to accomplish this. An array of arbitrary string key-value pairs can be stored in the route data attribute. Static data can be used to store information like page titles, breadcrumb text, and other read-only data.

Consider the following route, which has the data property set.

{ path: 'static', component: StaticComponent, data :{ id:'1', name:"Angular"}},

When the StaticComponent is rendered, the Angular Router will pass the id:'1', name:"Angular" The data value will be stored in the ActivatedRoute service's data property.

Subscribing to the activatedroute.data property, as seen below, allows us to read the data.

ngOnInit() {
      this.activatedroute.data.subscribe(data => {
          this.product=data;
      })
}

Passing Dynamic data to a Route

The state object in Angular Version 7.2 added the ability to send dynamic data or a user-defined object. History API stores the state object.

Providing the State value

There are two ways to provide the state.

Using routerLink directive

<a [routerLink]="['dynamic']" [state]="{ id:1 , name:'Angular'}">Dynamic Data</a>

Using navigateByUrl

this.router.navigateByUrl('/dynamic', { state: { id:1 , name:'Angular' } });

Accessing the state value

The state can be obtained by calling the router's getCurrentNavigation function (which works only in the constructor)

this.router.getCurrentNavigation().extras.state

Alternatively, using the ngOnInit's history.state.

console.log(history.state)

or use the Location Service's getState function. This procedure can be used. Angular 8+ is an advanced version of Angular.

import { Location } from '@angular/common';
 
export class SomeComponent
{
  products:Product[];
 
  constructor(private location:Location){
  }
 
  ngOnInit() {
    console.log(this.location.getState());
  }
}

Passing Data to the Routes Example

Let's create a basic project to show how to send data to the route.

Passing static data example

import {Component, OnInit} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
 
@Component({
     template: `<h1>Passing Static Data Demo</h1>
         {{product  | json}}`
})
export class StaticComponent implements OnInit {
 
     product:any;
     constructor(private activatedroute:ActivatedRoute) {
     }
 
     ngOnInit() {
          this.activatedroute.data.subscribe(data => {
               this.product=data;
           })
     }
}

The route's static data is passed to the static component. To receive the product data, it subscribes to the activatedroute.data property, as seen above.

Passing dynamic data (or object) example

import {Component, OnInit, ChangeDetectorRef} from '@angular/core';
import { ActivatedRoute, Router, NavigationStart } from '@angular/router';
import { map, filter} from 'rxjs/operators';
import { Observable} from 'rxjs/observable';
 
@Component({
     template: `<H1>Passing Dynamic Data Demo</H1>
 
     {{ product | json }}`
})
export class DynamicComponent implements OnInit {
 
     product;
 
     constructor(private router:Router, private activatedRoute:ActivatedRoute) {
          console.log(this.router.getCurrentNavigation().extras.state);
     }
 
     ngOnInit() {
          //console.log(history.state);
          this.product=history.state;
     }
 
}

Dynamic data is obtained by the Dynamic Component. To get to the product data, we use the history.state function. We may also use this.router as an alternative. To achieve the same result, use getCurrentNavigation().extras.state. It's important to remember that getCurrentNavigation is only used in the constructor. If used elsewhere, it will return null.

Add the following code under the home.component.ts file:

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
 
@Component({
  template: `
     <ul>
       <li><a [routerLink]="['/static']">Static Data</a></li>
       <li><a [routerLink]="['/dynamic']" [state]=product>Dynamic Data</a></li> 
    </ul>
   
    <p>Id :   <input type="text" [(ngModel)]="product.id" > </p>
    <p>name :<input type="text" [(ngModel)]="product.name" > </p>
    <button (click)="gotoDynamic()" >Goto Dynamic Component</button>`
})
export class HomeComponent {
  
  public product = { id:'1', name:"Angular"};
 
  constructor(private router : Router) {
  }
 
  gotoDynamic() {
    //this.router.navigateByUrl('/dynamic', { state: { id:1 , name:'Angular' } });
    this.router.navigateByUrl('/dynamic', { state: this.product });
  }
}

To transfer data to the dynamic component, we use routerLink and navigateByUrl in HomeComponent. You may even update the data before providing it to the dynamic route by using the form fields.

Add the following code under the app.routes.ts file:

import { Routes } from '@angular/router';
 
import { StaticComponent} from './static.component'
import { DynamicComponent } from './dynamic.component';
import { HomeComponent } from './home.component';
 
export const appRoutes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'static', component: StaticComponent, data :{ id:'1', name:"Angular"}},
  { path: 'dynamic', component: DynamicComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' }
];

The data property is used to set the static data for StaticComponent.

Add the following code under the app.component.ts file:

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `<div class="container">
 
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <a class="navbar-brand" [routerLink]="['/']"><strong> {{title}} </strong></a>
      </div>
    </div>
  </nav>
  
  <router-outlet></router-outlet>
  
  </div>`
})
export class AppComponent {
  title = 'Routing Module - Passing Dynamic / Static data route';
}

Add the following code under the app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
 
import { RouterModule } from '@angular/router';
 
import { AppComponent } from './app.component';
import { StaticComponent} from './static.component'
 
 
import { appRoutes } from './app.routes';
import { DynamicComponent } from './dynamic.component';
import { HomeComponent } from './home.component';
 
@NgModule({
  declarations: [
    AppComponent,StaticComponent,DynamicComponent,HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, run the application and see what the output screen that looks like below.

How To Pass Data To Route In Angular

Conclusion

In this article, we learned how to pass data to route in angular. it can be static or dynamic.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post