stephenad
stephenad

Reputation: 55

Angular 2 Opening a different form with a passed in parameter

Hope someone can advise the best way to achieve what I want.

I have a user grid where you can click edit it then goes to the manage user form.

What I want to do is pass the selected user id over to the manage user form and display this user, how best would I go about achieving this?

Thanks Andy

Upvotes: 0

Views: 51

Answers (1)

Veena K. Suresh
Veena K. Suresh

Reputation: 1002

In your grid.component.html, when user clicks on a grid edit button, call a function and pass the corresponding grid data id as shown below.

<button (click)="goToManageForm(gridId)"> Edit</button>

In your grid.component.ts, pass the id as a param to the manageForm component.

private goToManageForm(id:any){
   this.router.navigate([`/manageForm/${id}`]);
}

In your routing component, add a route to manageForm component which expects a parameter.

const routes: Routes = [

{
    path: '',
    component: MyMainComponent,
    canActivate: [AuthGuard],
    children: [
      { path: 'grid',    component: GridComponent },
      { path: 'manageForm/:gridId',    component: ManageFormComponent },
]
}

You can access the passed grid id in the manageForm.component.ts as shown below.

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

export class manageFormComponent {

   private subscription:Subscription;
   private gridId:any; 

   constructor(private activatedRoute:ActivatedRoute){}

   ngOnInit(): void {

      // subscribe to router event
      this.subscription = this.activatedRoute.params.subscribe(
        (param: any) => {
           if(typeof param['gridId'] !== 'undefined' && param['gridId'].trim !='' ){ 
              this.gridId = param['gridId'];
           }
      });
   }
 }

Now the passed gridId will be accessible in this.gridId

Upvotes: 1

Related Questions