0

Hi I have a table in a page where it shows the list of all students And when we click on view button in the table, it takes to other page where it shows the details of specific student.

enter image description here

The list of students is component 1 and student details is component 2.

How do I send data when they click on 'View/Edit' button to other component ?

1st -> student-list.component.ts

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

    @Component({
      selector: 'app-student-list',
      templateUrl: './student-list.component.html',
      styleUrls: ['./student-list.component.scss']
    })
    export class StudentsListComponent implements OnInit {

      userData: any;
      selectedUser: any;

      constructor(public router: Router, public route: ActivatedRoute) { }

     ngOnInit() {
          this.getStudentList();
  }

  getStudentList() {
    this.http.get<Student>('*url*')
      .subscribe(data => {
        this.student = data;
      });
  }
    }

2nd -> student.component.ts

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

@Component({
  selector: 'app-student-selected',
  templateUrl: './student.component.html',
  styleUrls: ['./student.component.scss']
})
export class SelectedStudentComponent implements OnInit {


  constructor(public router: Router, public route: ActivatedRoute) { }

  ngOnInit() {
    }


}
yer
  • 1,454
  • 2
  • 16
  • 33
  • 1
    use [@Input()](https://angular.io/guide/component-interaction) if you want to share data between a parent and a child component, else use services to share data between components. In your case on click of 'View/Edit' button get the data and store in the Service and when you route to the student component populate the data from service using ngOnInit() – Avinash Jun 18 '18 at 16:12
  • I can have a service to get the list of all students. But how do I get only specific student details when clicked on sview button? – yer Jun 18 '18 at 16:13
  • in the same service on click of 'View/Edit' button have a method setStudentData() where you can pass the data of that student you got and store in a variable, then retrieve the student data using another method getStudentData() which you can use in ngOnInit() of the student component. – Avinash Jun 18 '18 at 16:18
  • can you show me an example – yer Jun 18 '18 at 16:22
  • added as an answer as its difficult to have the same in comment – Avinash Jun 18 '18 at 16:35
  • Is the `StudentDetailComponent` on its own route? Since you said it takes to another page, I figure it has its own route. You can attach the Student ID (the one that gets clicked on) as URL Parameter. For e.g: `/students/` goes here. Then in StudentDetailComponent, you can use ActivatedRoute to get the parameter and fetch the student detail with the Student ID. – Chau Tran Jun 18 '18 at 16:35
  • @yer, You want the two component at time? If not, normally you use a router like /student:/id see https://angular.io/guide/router#route-definition-with-a-parameter – Eliseo Jun 18 '18 at 16:36
  • @ChauTran The solution you suggested to send the param in the route and then access it using ActivatedRoute and then make a service call will definitely work but it will be difficult to handle especially in the scenario when the user navigates back and forth using the browser back and forward button, you will end up triggering multiple service calls to get the same data hence its better to make the service call, store the data and then route to the student component. – Avinash Jun 18 '18 at 16:53
  • @Avinash It totally depends on the use-case and how the API returns ;) What if the `list` only contains certain amount of information of the `students` but a `studentDetail` contains much more information? – Chau Tran Jun 18 '18 at 16:55

2 Answers2

1

In your student-list.component.html use event binding to call a method in your student-list.component.ts file where you can update your service and then route to the student.component.ts

<button (click)="loadStudentData($event, studentId)">View/Edit</button>

have a service store the student data

xyz.service.ts

studentData = {};

setStudentData(data){
 this.studentData = data;
}

getStudentData(){
 return this.studentData;
}

In your student-list.component.ts import the service

loadStudentData(e, studentId){
 //make a service call to get the data using the studentId
  this.service.setStudentData(data);
 //then route to student.component.ts
}

In your student.component.ts import the service

private currentStuData = {};
ngOnInit(){
 //have a local variable to which you can assign the value from service 
  this.currentStuData = this.service.getStudentData();
 //use currentStuData in your template
}

Here i considered your data as an object you can handle it depending on the type of data you want to store using the service.

Avinash
  • 1,245
  • 11
  • 19
0

You can use a common service to share the student data between components.

here it is

import { Injectable } from '@angular/core';

@Injectable()
export class StudentService   {

  public student: BehaviorSubject<Object> = new BehaviorSubject<Object>(null);

  constructor() {}


}

inject this service to your both component (like below) :

constructor(protected service : StudentService){}

and subscribe student of StudentService in component 2(ur view component) like below :

//declare student and its subscription like below in component 2
public student : Object;
public studentSubscription : Subsription ;

public subscribeStudent(){
this.studentSubscription = this.service.student.subscribe(data => {
this.studnet = data;
});
}

//call above method from constructor or ngOninit

now into component 1 write a method which will be called when you click on view like below :

public viewStudent(student:any){
this.service.student.next(student);

  this.router.navigate( [
        'student',
         student[ 'id' ]
      ] );
}

html of component 1 should be similar like below :

<div *ngFor = "let student of studentList">

<html to display row in first component....>
...  
<button type="button" (click)="viewStudent( student )">
                        View/Edit
 </button>
...
</div> 
Atul
  • 521
  • 1
  • 7
  • 20