ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Angular Pass Data to Route: Dynamic/Static

Angular allows us to pass data through the route. The route data can be either static or dynamic. The static data use the Angular route data property, where you can store arbitrary data associated with that specific route. To pass dynamic data (or an object), we can use the history state object. The Routed Component can then retrieve the dynamic data from the history state object.

Various ways of passing route data

Angular components can share data in many ways. The parent can communicate with their child using @Input directive. A child can pass data to the Parent using the @Output & EventEmitter. The parent can use the @ViewChild to access the child component. In case of components are unrelated then we can use the Angular Services to Share data between them.

We looked at how to navigate using the RouterLink directive in the previous tutorials.We can also share data between components using the route. Angular can pass data through the route in several ways.

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

In this article, we look at how to pass static or dynamic data using the Route. i.e. items 4 & 5 in the above list.

Passing static data to a route

We can configure the static data at the time of defining the route. This is done by using the Angular route data property of the route. The route data property can contain an array of arbitrary string key-value pairs. You can use the static data to store items such as page titles, breadcrumb text, and other read-only, static data

For Example, consider the following route with the data property set

                              

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

The Angular Router will pass the { id:'1', name:"Angular"} when the StaticComponent is rendered. The data value will be located in the data property of the ActivatedRoute service

We can then read the data by subscribing to the activatedroute.data property as shown below

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

Passing Dynamic data to a Route

The option to pass the dynamic data or a user-defined object was added in Angular Version 7.2 using the state object. The state object is stored in History API

Providing the State value

The state can be provided in two ways

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' } });
 
                            
                        

NavigationId

navigationId is a number, which is incremented every time we navigate from one route to another. Angular uses it to identify every navigation. The Router will add a navigationId property to the state object. Because of that, we can only assign an object to the State object.

Hence we cannot store primitive types like strings or numbers etc. For example, the following code results in an error because we are passing a string.

                              

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

You can only assign an object to the state object. The following code is ok.

                              

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

Accessing the state value

The state can be accessed by using the getCurrentNavigation method of the router (works only in the constructor)

                              

this.router.getCurrentNavigation().extras.state
                            
                        

Or use the history.state in the ngOnInit.

                              

console.log(history.state)
                            
                        

or use the getState method of the Location Service. This method is available in Angular 8+

                              
 
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 us build a simple project to demonstrate how to pass data to the route

Passing static data example

static.component.ts
                              

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 static component gets the static data configured in the route. It subscribes the activatedroute.data property to get the product data as shown above.

Passing dynamic data (or object) example

dynamic.component.ts
                              

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;
     }
 
}
 
                            
                        

The Dynamic Component gets dynamic data. We use the history.state to access the product data. Alternatively, we can use the this.router.getCurrentNavigation().extras.state to achieve the same. Please remember getCurrentNavigation only works in the constructor. It will return null if used elsewhere.

home.component.ts
                              

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 });
  }
}
 
                            
                        

In HomeComponent, we have used routerLink & navigateByUrl to pass the data to the dynamic component. You can also use the form fields to change the data, before passing it to the dynamic route.

app.routes.ts
                              

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' }
];
 
 
                            
                        

Here the static data is set for StaticComponent using the data property.

app.component.ts
                              

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';
}
 
                            
                        
app.module.ts
                              

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 { }
 
                            
                        
image