Search code examples
angularcomponentsrouterlink

data between two components Angular 4


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() {
    }


}

Solution

  • 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.