How to pass value(index) through navigateByUrl

301 views Asked by At

I have created two components home where I will show minute details about a Employee, and view where I will show complete details about a Employee.

My home.component.html is as follows:

<header>Welcome Home</header>
<br>
<div class="container panel panel-default" *ngFor="let employee of employeeList;">
 <div class="panel-heading">
  <h3 class="panel-title">{{employee.firstName}} {{employee.lastName}}</h3>
 </div>
 <div class="panel-body">
  <div class="col-xs-10">
   <div class="row vertical-align">
    <div class="col-xs-8 offset-md-2">
     <div class="row">
      <div class="col-xs-6">
       First Name
      </div>
      <div class="col-xs-6">
       {{employee.firstName}}
      </div>
     </div>
     <div class="row">
      <div class="col-xs-6">
       Last Name
      </div>
      <div class="col-xs-6">
       : {{employee.lastName}}
      </div>
     </div>
     <div class="row">
      <div class="col-xs-6">
       Gender
      </div>
      <div class="col-xs-6">
       : {{employee.gender}}
      </div>
     </div>
     <div class="row">
      <div class="col-xs-6">
       Department
      </div>
      <div class="col-xs-6">
       : {{employee.department}}
      </div>
     </div>
     <div>
      <button class="btn btn-primary" (click)="viewEmployee(employee.id)">
       View
      </button>
      &nbsp;
      <button class="btn btn-primary" (click)="editEmployee(employee.id)">
       Edit
      </button>
     </div>
    </div>
   </div>
  </div>
 </div>
</div>

My home.component.ts is as follows:

import { Component, NgModule, OnInit } from '@angular/core';
import { Router, RouterModule, Routes } from '@angular/router';
import employees from './../employeeDetails/employees.json';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
  constructor(private router: Router) {
  }
  public employeeList: {
    id: number;
    firstName: string;
    lastName: string;
    gender: string;
    age: number;
    email?: string;
    phoneNumber?: number;
    department: string;
  }[] = employees;
  ngOnInit(): void {

  }

  viewEmployee(id): any {
    this.router.navigateByUrl('/view');
  }

  editEmployee(i): any {
    this.router.navigateByUrl('/edit');
  }
}

When I click on button available in home component, it has to carry the index or id of the employee. and show only specific details about that employee. Presently, when I click view button, it is displaying all the details of all employees.

My view.component.html is as follows:

<header>View Page</header>
<br>
<div class="container panel panel-default" *ngFor="let employee of employeeList;">
    <div class="panel-heading">
        <h3 class="panel-title">{{employee.firstName}} {{employee.lastName}}</h3>
    </div>
    <div class="panel-body">

        <div class="col-xs-10">
            <div class="row vertical-align">

                <div class="col-xs-8 offset-md-2">

                    <div class="row">
                        <div class="col-xs-6">
                            First Name
                        </div>
                        <div class="col-xs-6">
                            : {{employee.firstName}}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6">
                            Last Name
                        </div>
                        <div class="col-xs-6">
                            : {{employee.lastName}}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6">
                            Gender
                        </div>
                        <div class="col-xs-6">
                            : {{employee.gender}}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6">
                            Age
                        </div>
                        <div class="col-xs-6">
                            : {{employee.age}}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6">
                            Email
                        </div>
                        <div class="col-xs-6">
                            : {{employee.email}}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6">
                            Phone Number
                        </div>
                        <div class="col-xs-6">
                            : {{employee.phoneNumber}}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6">
                            Department
                        </div>
                        <div class="col-xs-6">
                            : {{employee.department}}
                        </div>
                    </div>
                    <div>
                        <button class="btn btn-primary" (click)="editEmployee()">Edit</button>
                    </div>

                </div>

            </div>

        </div>
    </div>
</div>

My view.comonent.ts is as follows:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import employees from './../employeeDetails/employees.json';

@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {

  constructor(private router: Router) { }
  public employeeList: {
    id: number;
    firstName: string;
    lastName: string;
    gender: string;
    age: number;
    email?: string;
    phoneNumber?: number;
    department: string;
  }[] = employees;
  ngOnInit(): void {
  }
  editEmployee(): any {
    this.router.navigateByUrl('/edit');
  }
}

In total I have 3 employees, which I have specified in employee.json file. Which is as follows:

[
    {
        "id": 1,
        "firstName": "Abhi",
        "lastName": "A B",
        "gender": "male",
        "age": 25,
        "email": "[email protected]",
        "phoneNumber": 8888888888,
        "department": "IT"
    },
    {
        "id": 1,
        "firstName": "Amogh",
        "lastName": "A M",
        "gender": "male",
        "age": 25,
        "email": "[email protected]",
        "phoneNumber": 8888888888,
        "department": "IT"
    },
    {
        "id": 1,
        "firstName": "Harsha",
        "lastName": "H A",
        "gender": "male",
        "age": 25,
        "email": "[email protected]",
        "phoneNumber": 8888888888,
        "department": "IT"
    }
]

Please help.

2

There are 2 answers

0
Elmehdi On

Just follow along with this video: link
it's explaining exactly what you want to achieve with angular router.

EDIT:

You can visit this demo too: link, and notive the relationship between hero-list component and hero-detail component, both of them inside heroes folder.
for example, in the demo app, if you click on heroes you navigate to hero-list component, and after that if you click on Dr Nice for example:

enter image description here

you navigate to hero-detail component, but with data corresponding to Dr Nice:

enter image description here

15
EVeras On

You may pass the id like this:

this.router.navigateByUrl(`/view/${id}`);

And then on the view component get it like this:

constructor(private router: Router, private route: ActivatedRoute) { }
///
ngOnInit() {
   this.route.params.subscribe((params) => {
      const employeeId = params.id;
    });
}

This is a code sandbox that might help you: https://codesandbox.io/s/flamboyant-rubin-x2fuc?file=/src/app/view/view.component.ts

Important points:

  • The json file has id 1 for all employees, I changed this on the codesandbox for it to work well.
  • The view component html should not have an ngFor since you want only one employee on this view.
*ngFor="let employee of employeeList;

I removed this on the sandbox from the view.component.html

  • This is the core of the answer. Adds a local variable to store the employee and then assigns it filtering from the json using the id from params.
  employee;
  
  ngOnInit(): void {
    this.route.params.subscribe((params) => {
      const employeeId = params.id;
      this.employee = employees.filter((e) => e.id === +employeeId)[0];
    });
  }