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 Route Params

In this tutorial, we learn how to pass route params (Route Parameters) to the Route in Angular. First, let us look at how to define the route, which accepts the parameter. We then learn how to pass the angular route params to the route using the routerLink directive. Finally, we learn how to retrieve the parameters using the ActivatedRoute Service. The parameters can be retrieved by either reading the snapshot property or by subscribing to the paramMap or params observation.

What are Angular Route Parameters?

There are many scenarios, where you need to pass parameters to the route. For example, to navigate to the product detail view, we need to pass the id of the Product, so that component can retrieve it and display it to the user. This is where we use the Route Parameters (or Angular Route Params)

The Route Parameters are a dynamic part of the Route and essential in determining the route.

For example, consider the following route

                              
 
{ path: 'product', component: ProductComponent }
                            
                        

The above route match only if the URL is /product

To retrieve the product details, our URL should look something like

/product/1 /product/2

Where the second URL segment ( 1 and 2 ) is the id of the product. The id is dynamic and changes as per the selected Product. To handle such a scenario angular router allows us to include route parameters , where we can send any dynamic value for a URL segment

How to Pass Parameters to Angular Route

Route Params Example Application

Let us build on the Application we built in the Angular Routing tutorial.

The application contains the Product and Product Details page. The Product detail page displays the product detail based on the Product Id passed in the URL. Since the Product Id is dynamic, we will pass it as a Route Parameter.

You can view the code from the stackblitz

Defining the Route

Our first task is to create a Route with a dynamic Parameter. We know how to define Route from the Routing & Navigation tutorial

We can define parameters by adding a forward slash followed colon and a placeholder (id) as shown below

app.module.ts
                              


{ path: 'product/:id', component: ProductDetailComponent }
                            
                        

Where id is the dynamic part of the Route.

Now above path matches the URLs /product/1,/product/2, etc.

If you have more than one parameter, then you can extend it by adding one more forward slash followed colon and a placeholder

                              

{ path: 'product/:id/:id1/:id2', component: ProductDetailComponent }
                            
                        

The name id, id1 & id2 are placeholders for parameters. We will use them while retrieving the values of the parameters.

Defining the Navigation

We, now need to provide both path and the route parameter routerLink directive.

This is done by adding the id of the product as the second element to the routerLink parameters array as shown below

                              

 
<a [routerLink]="['/Product', ‘2’]">{{product.name}} </a>
                            
                        

Which translates to the URL /product/2

OR

product.component.ts
                              

<a [routerLink]="['/Product', product.productID]">{{product.name}} </a>
                            
                        

Which, dynamically takes the value of the id from the product object.

You can also use the navigate method of the router object

                              

goProduct() {     
    this.router.navigate(
        ['/products'. product.productID] }
    ); 
}
 
                            
                        

Retrieve the parameter in the component

Finally, our component needs to extract the route parameter from the URL

This is done via the ActivatedRoute service from the angular router module to get the parameter value

ActviatedRoute

The ActivatedRoute is a service, which keeps track of the currently activated route associated with the loaded Component.

To use ActivatedRoute, we need to import it into our component

product-detail.component.ts
                              

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

Then inject it into the component using dependency injection

product-detail.component.ts
                              
product-detail.component.ts
 
constructor(private _Activatedroute:ActivatedRoute)
 
                            
                        

There are two properties that ActviatedRoute routes provide, which contain the Route Parameter.

  1. ParamMap
  2. Params

ParamMap

The Angular adds the map of all the route parameters in the ParamMap object, which can be accessed from the ActivatedRoute service

The ParamMap has three methods, which makes it easier to work with the route parameters.

get method retrieves the value of the given parameter.

getAll method retrieves all parameters

has method returns true if the ParamMap contains a given parameter else false

Params

The Angular ActviatedRoute also maintains the Route Parameters in the Params array. The Params array is a list of parameter values, indexed by name.

Reading the Route Parameters

There are two ways in which you can use the ActivatedRoute to get the parameter value from the ParamMap object.

  1. Using the Snapshot property of the ActivatedRoute
  2. Subscribing to the paramMap or params observable property of the ActivatedRoute

Using Snapshot

The snapshot property returns the current value of the route. It does not contain any observable. Hence if the value changes after you retrieve the values, you will not be notified of it. The snapshot contains both paramMap & params array. You can use any of them to read the value of id.

The following code reads the value from the paramMap object.

                              

this.id=this._Activatedroute.snapshot.paramMap.get("id");
                            
                        

Code to read the router parameter from the params array.

                              

this.id=this._Activatedroute.snapshot.params["id"];
                            
                        

Using Observable

The ActivatedRoute also contains the paramMap & params observable. We can subscribe to it and listen for changes. The paramMap observable emits the paramMap object, while the params observable emits the params array.

The following code subscribes to the paramMap observable. We use the get method to read the value of id.

                              

this.id=this._Activatedroute.snapshot.params["id"];
                            
                        

The code to subscribe to the params observable

                              

this._Activatedroute.params.subscribe(params => { 
    this.id = params['id']; 
});
 
 
                            
                        

Which one to use? snapshot or observable

We usually retrieve the value of the parameter in the ngOnInit life cycle hook, when the component is initialized.

When the user navigates to the component again, and if the component is already loaded then, Angular does not create the new component but reuses the existing instance. In such circumstances, the ngOnInit method of the component is not called again. Hence you need a way to get the value of the parameter.

By subscribing to the paramMap observable (or to the params observable), you will get a notification when the value changes. Hence you can retrieve the latest value of the parameter and update the component accordingly.

The above difference is explained in our next tutorial Angular child routes tutorial.

Passing Parameters to Route: Example

Here is the complete list of codes.

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>
        <ul class="nav navbar-nav">
          <li><a [routerLink]="['home']">Home</a></li>
          <li><a [routerLink]="['product']">Product</a></li>
          <li><a [routerLink]="['contact']">Contact us</a></li>
        </ul>
      </div>
    </nav>
 
    <router-outlet></router-outlet>
  </div>
  
  `,
})
export class AppComponent {
  title = 'Route Parameters Demo';
}
                            
                        

The routerlink directive code creates the HTML link and binds the click event of the link to a route. Clicking on the Product link will direct us to the product route. The routes are defined in the app.module.

                              

 
<li><a [routerLink]="['home']">Home</a></li>
<li><a [routerLink]="['product']">Product</a></li>
<li><a [routerLink]="['contact']">Contact us</a></li>
                            
                        
product.ts
                              


export class Product { 
 
  constructor(productID:number,    name: string ,   price:number) {
      this.productID=productID;
      this.name=name;
      this.price=price;
  }
 
  productID:number ;
  name: string ;
  price:number;
 
}
                            
                        
product.service.ts
                              

import { Observable } from 'rxjs';
import { Product } from './product';
 
export class ProductService {
  public getProducts() {
    let products: Product[];
 
    products = [
      new Product(1, 'Memory Card', 500),
      new Product(2, 'Pen Drive', 750),
      new Product(3, 'Power Bank', 100),
    ];
 
    return products;
  }
 
  public getProduct(id) {
    let products: Product[] = this.getProducts();
    return products.find((p) => p.productID == id);
  }
}
 
                            
                        
product.component.ts
                              

import { Component, OnInit } from '@angular/core';
 
import { ProductService } from './product.service';
import { Product } from './product';
 
@Component,({
  template: `
  
  <h1>Product List</h1>
  <div class='table-responsive'>
      <table class='table'>
          <thead>
              <tr>
                  <th>ID</th>
                  <th>Name</th>
                  <th>Price</th>
              </tr>
          </thead>
          <tbody>
              <tr *ngFor="let product of products;">
                  <td>{{product.productID}}</td>
                  <td><a [routerLink]="['/product',product.productID]">{{product.name}} </a> </td>
                  <td>{{product.price}}</td>
              </tr>
          </tbody>
      </table>
  </div>
    
  `,
})
export class ProductComponent {
  products: Product[];
 
  constructor(private productService: ProductService) {}
 
  ngOnInit() {
    this.products = this.productService.getProducts();
  }
}
 
 
                            
                        

In the Product Component, we have added product.productID as the second argument to the routerLink parameters array.

                              

<a [routerLink]="['/product',product.productID]">{{product.name}} </a> 
                            
                        
product-detail.component.ts
                              

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
 
import { ProductService } from './product.service';
import { Product } from './product';
 
@Component,({
  template: `
  
  <h3>Product Details Page</h3>
 
 
product : {{product.name}}
price : {{ product.price}}
<p>
    <a class='btn btn-default' (click)="onBack()">Back </a>
</p>
  `,
})
export class ProductDetailComponent implements OnInit {
  product: Product;
  id;
 
  constructor(
    private _Activatedroute: ActivatedRoute,
    private _router: Router,
    private _productService: ProductService
  ) {}
 
  /* Using snapshot */
  //ngOnInit() {
  //  this.id = this._Activatedroute.snapshot.paramMap.get('id');
  //
  //  //You can use this also
  //  //this.id=this._Activatedroute.snapshot.params['id'];
 
  //  let products = this._productService.getProducts();
  //  this.product = products.find((p) => p.productID == this.id);
  //}
 
  /* Using Subscribe */
 
  sub;
 
  ngOnInit() {
    this.sub = this._Activatedroute.paramMap.subscribe((params) => {
      console.log(params);
      this.id = params.get('id');
      let products = this._productService.getProducts();
      this.product = products.find((p) => p.productID == this.id);
    });
 
    //You can also use this
    //this.sub=this._Activatedroute.params.subscribe(params => {
    //    this.id = params['id'];
    //    let products=this._productService.getProducts();
    //    this.product=products.find(p => p.productID==this.id);
    //});
  }
 
  ngOnDestroy() {
    if (this.sub) this.sub.unsubscribe();
  }
 
  onBack(): void {
    this._router.navigate(['product']);
  }
}
 
 
                            
                        

In the ProductDetailComponent, we have imported router and ActivatedRoute from the angular router module

                              

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

In the constructor, we inject the ActivatedRoute, Router service along with ProductService

                              

constructor(private _Activatedroute:ActivatedRoute,
        private _router:Router,
        private _productService:ProductService){
   }
 
                            
                        

Finally, we use ngOninit life cycle hook to retrieve the value of the id parameter and use that value to retrieve the details of the product.

Note that, there are two ways, by which you can retrieve the data.

Using snapshot
                              

/* Using snapshot */
  ngOnInit() {
    this.id = this._Activatedroute.snapshot.paramMap.get('id');
  
    //You can use this also
    //this.id=this._Activatedroute.snapshot.params['id'];
 
    let products = this._productService.getProducts();
    this.product = products.find((p) => p.productID == this.id);
  }
 
                            
                        

Subscribing to paramMap observable

We used the snapshot method to retrieve the parameter in the ProductDetailcomponet.ts. To Subscribe to params remove the ngOnInit and replace it with the following code

We recommend you use the subscribe method as it offers the benefit of responding to the parameter changes dynamically.

                              

sub;
 
  ngOnInit() {
    this.sub = this._Activatedroute.paramMap.subscribe((params) => {
      console.log(params);
      this.id = params.get('id');
      let products = this._productService.getProducts();
      this.product = products.find((p) => p.productID == this.id);
    });
 
    //You can also use this
    //this.sub=this._Activatedroute.params.subscribe(params => {
    //    this.id = params['id'];
    //    let products=this._productService.getProducts();
    //    this.product=products.find(p => p.productID==this.id);
    //});
  }
 
                            
                        
app.module.ts
                              

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
 
import { RouterModule } from '@angular/router';
 
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
import { ContactComponent } from './contact.component';
import { ProductComponent } from './product.component';
import { ErrorComponent } from './error.component';
import { ProductDetailComponent } from './product-detail.component';
 
import { ProductService } from './product.service';
 
import { HttpClientModule } from '@angular/common/http';
import { Routes } from '@angular/router';
 
export const appRoutes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'product', component: ProductComponent },
  { path: 'product/:id', component: ProductDetailComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: '**', component: ErrorComponent },
];
 
@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ContactComponent,
    ProductComponent,
    ErrorComponent,
    ProductDetailComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes),
  ],
  providers: [ProductService],
  bootstrap: [AppComponent],
})
export class AppModule {}
 
 
                            
                        

The route to the Product Detail Component

                              

{ path: 'product/:id', component: ProductDetailComponent },
                            
                        
contact.component.ts
                              


import { Component } from '@angular/core';
 
@Component({
  template: `<h1>Contact Us</h1>
                <p>TekTutorialsHub </p>
                `,
})
export class ContactComponent {}
 
 
                            
                        
home.component.ts
                              

import { Component } from '@angular/core';
 
@Component({
  template: `<h1>Welcome!</h1>
              <p>This is Home Component </p>
             `,
})
export class HomeComponent {}
 
 
                            
                        
error.component.ts
                              
 
import { Component } from '@angular/core';
 
@Component,({
  template: `<h1>Page not found</h1>
               <p>This is a Error Page</p>
              `,
})
export class ErrorComponent {}
 
 
                            
                        
image

ActivatedRoute

The ActivatedRoute service has a great deal of useful information including:

url: This property returns an array of Url Segment objects, each of which describes a single segment in the URL that matched the current route.

params: This property returns a Params object, which describes the URL parameters, indexed by name.

queryParams: This property returns a Params object, which describes the URL query parameters, indexed by name.

fragment: This property returns a string containing the URL fragment.

Snapshot: The initial snapshot of this route

data: An Observable that contains the data object provided for the route

Component: The component of the route. It’s a constant

outlet: The name of the RouterOutlet used to render the route. For an unnamed outlet, the outlet name is primary.

outlet: The name of the RouterOutlet used to render the route. For an unnamed outlet, the outlet name is primary.

routeConfig: The route configuration used for the route that contains the origin path.

parent: an ActivatedRoute that contains the information from the parent route when using child routes.

firstChild: contains the first ActivatedRoute in the list of child routes.

children: contains all the child routes activated under the current route

pathFromRoot: The path from the root of the router state tree to this route

Summary

We looked at how to pass parameters or data to the Route. The parameters are passed to the route by using routerLink parameters in the routerLink directive. We retrieve the parameters from ActivatedRoute service by reading the paramMap collection of the snapshot object or by subscribing to the paramMap observable.