How to Pass and Get State Params in Angular2

Posted By : Rohit Goyal | 29-Jun-2017

Introduction:-

In some cases we have to send the parameter from one state to another.So, in such cases we have to pass the data from one state
and in the state which we want to reterive the data we have get state params.Let's see how it works.

Step:1 - Passing the parameter in state

First of all we have the pass the parameter in state. for this we have to import router service.In click of navigateUser()
we are passing paramter in state.

            @Component({
              selector:'login-component',
              template: `
               <button (click)="navigateUser()">Navigate</button>
               `,
             })

          export class LoginComponent{
          constructor(private r:Router){ }
          navigateUser():void{
            this.r.navigate(['edit-todo',1]);
       }
}
       

Step:2- Getting Parameter in routes.

You have to transfer parameter in your path variable.

            import { RouterModule } from '@angular/router';
            import { EditToDoComponent }  from './crud/editToDo.component';

            @NgModule({
            imports:      [RouterModule.forRoot(
            [
             {path:'edit-todo/:id',component:EditToDoComponent}
            ]
            })
       

Step:3- Reterving Parameter in your component:-

By using ActivatedRoute route service you can reterive your state param through for each loop

            import { Router, ActivatedRoute } from '@angular/router'
            constructor(private r:Router, private ac:ActivatedRoute){
           // we need to take thus inside self
           var self = this;

          // read the route parameter in constructor
          ac.params.forEach(function(param:any){
            console.log("param value is " + param['id']);
            self.todoid = param['id'];
            console.log(self.todoid);
           });
          }
       

That's it.
If you have any query please contact on my skype Id:- rohit.oodles

 

About Author

Author Image
Rohit Goyal

Rohit is an experienced Frontend Developer, having good experience in HTML5, CSS3, Bootstrap, Jquery, AngularJS, Angular4/5, Restful API Integration, ES6 . His hobbies are playing cards and cricket.

Request for Proposal

Name is required

Comment is required

Sending message..