How to pass and get parameter with Router params in Angular 4.?

Viewed 1684

I want to pass an id with url using Router in Angular. And i have to fetch that value on another page. Like I have a student list. On click of edit button belongs to particular student on the list. The id of that student pass to edit student details page. After fetching that studentId I want show existing details in the input fields.

So How i can do this?

this is my example path

 { path: 'school-students-list', component: studentsListPageComponent },
  { path: 'edit-student-details', component: studentEdit },
2 Answers

Give the route a parameter like this:

{ path: 'edit-student-details/:id', component: studentEdit }

And then use ActivatedRoute in that component to access the route parameters. Import it from @angular/router

import { ActivatedRoute, Params } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

Inject this into the constructor

private routeSub: Subscription;

constructor(private route: ActivatedRoute) {}

On init, subscribe to route parameters

ngOnInit(): void {
    this.routeSub = this.route.params.subscribe((params: Params): void => {
        const id = params['id'];
    });
}

Always a good idea to unsubscribe on destroy

ngOnDestroy(): void {
    this.routeSub.unsubscribe();
}

And to link to this page, passing in their member ID, do this on your student listings page:

<a [routerLink]="['/edit-student-details', memberId]">Edit</a>

To navigate via a component method, inject Router from @angular/router and then when you want to navigate, use this.router.navigate(['/edit-student-details', memberId]);

Import ActivatedRoute from @angular/router

import { ActivatedRoute, Router } from '@angular/router';

Access parameter from constructor:

constructor(private route: ActivatedRoute) {
    let id = +this.route.snapshot.params['id'];
    // use the id here
}
Related