5

I have a routerLink attached to the lead value in a table I have created in the HTML of an angular2 component. Upon clicking that table value, I want the routerLink to not only send to the next component but also bring the chosen value to the next component.

Example of current code

<a [routerLink]="['/Records']" ><td> {{Member.Name}} <td></a>

I have the link so it is sending to the Records page, however how do I send the name to that component so that I can display the specific record that I am trying to display?

Matt Fazzini
  • 141
  • 1
  • 14

3 Answers3

8

Add a route parameter to the url and then access that value using the ActivatedRoute.

Route Definition
{ path: "Records/:name", component: RecordsComponent }
Link
<a [routerLink]="['/Records', Member.Name]" ><td> {{Member.Name}} <td></a>
Get Value
@Component({
    ...
})
export class RecordsComponent implements OnInit {

    constructor(private _route: ActivatedRoute) { }

    ngOnInit(){
        this._route.params.subscribe((params) => {
        var recordName = params["name"];
        //load record data
   });
}
Community
  • 1
  • 1
Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51
  • 1
    What is the import that I need to use to be able to implement OnInit? – Matt Fazzini Feb 27 '17 at 20:43
  • import {OnInit} from '@angular/core'; – Teddy Sterne Feb 27 '17 at 20:44
  • 1
    I have correctly implement OnInit and am no longer getting an error, however, I am getting another error that says it cannot find the name ngOnInit. – Matt Fazzini Feb 27 '17 at 21:00
  • 1
    Yes that did it! Now just one more question: is there a way that I can use that recordName variable outside of the ngOnInIt function? (I am trying to send that name to an api call function in the same component) – Matt Fazzini Feb 27 '17 at 21:20
  • You could make recordName a property on your component and set it as `this.recordName = ...` or just all the API with the. And you received inside the subscription to the route params. – Teddy Sterne Feb 27 '17 at 21:33
  • 1
    Thank you, Teddy, I am forever in debt to you. – Matt Fazzini Feb 27 '17 at 21:43
4

define your route like this:

{ path: 'Records/:id', component: xxx }

declaratively:

<a [routerLink]="['/Records', Member.name]">{{ Member.name }}</a>

programmatically:

goToMemberDetails(name) {
   this.router.navigate(['/Records', name]);
 }
hannes neukermans
  • 12,017
  • 7
  • 37
  • 56
0
@Component({
    ...
})
export class RecordsComponent implements OnInit {

    constructor(private _route: ActivatedRoute) { }

    ngOnInit(){
        this._route.params.subscribe((params) => {
        var recordName = params["name"];
        //load record data
   });
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Siddhu
  • 1