Categories
Angular

pass value between two components using the route in angular

In this tutorial, we will learn about pass value between two components using the route in angular

In many scenarios, we need to pass one or two parameters from one component to another component

We can pass a value in various ways, But in this tutorial, we go to pass value between components using the route

For this tutorial, We are going to pass student id from the student list on click

By default, we will define routing as like below in-app-routing.module.ts

{ path: 'student', component: StudentDetailsComponent }

We need to pass id along with the student route like /student/1from the student list page

We can receive those route param value in student details page using ActivatedRoute

import { ActivatedRoute } from '@angular/router';
Sending value from first component

Here we are using pass value while clicking a hyperlink. via router link, we are defining the student id value as like below

<a [routerLink]="['/student', studentId]">{{name}} </a>
Routing Syntax

We need to mention in app.routing.module.ts about the parameter as like below
{ path: 'student/:id', component: StudentDetailsComponent }

app.routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { StudentDetailsComponent } from './component/student-details/student-details.component';


const routes: Routes = [
  { path: 'student/:id', component: StudentDetailsComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Receiving value in second component

As mentioned above we are going to use activedRoute to retrieve the value

this.studentId = this.activeParms.snapshot.paramMap.get("id");
Student-details-component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({

  selector: 'app-student-details',
  templateUrl: './student-details.component.html',
  styleUrls: ['./student-details.component.css']
})
export class StudentDetailsComponent implements OnInit {

  constructor(private activeParms: ActivatedRoute) { }
  studentId: string;
  ngOnInit(): void {
    this.studentId = this.activeParms.snapshot.paramMap.get("id");
  }

}
Conclusion

In this post, we looked about to pass value between two components using the route in angular

Related Articles

https://beginnersbug.com/ng-if-else-condition-in-angular-with-example/

Leave a Reply

Your email address will not be published. Required fields are marked *