Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Pass parameters to Route

I have a <a> tag like below,

<a [routerLink]="[/Person']">Person</a>

So I want to pass the person.id to this /Person router. How can I pass it & handle it on @RouteConfig like params in Angular 1

like image 568
DilumN Avatar asked Oct 14 '16 14:10

DilumN


1 Answers

Pass to router link:

<a [routerLink]="['/Person', person.id]">Person</a>

Handle in component:

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

Second way:

this.route.params.forEach(
   (params: Params) => {
       this.id = params['id'];
   }
);

In this example you have to inject ActivatedRoute (e.g as route property) like that:

constructor(private route: ActivatedRoute) {}

If you subscribe - it is important to unsubscribe Observable to prevent memory leaks.

Full example:

export class SimpleComponent implements OnInit, OnDestroy {
    private id: number;
    private route$: Subscription;
    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        this.route$ = this.route.params.subscribe(
            (params: Params) => {
                this.id = +params['id']; // cast to number
            }
        );
    }
    ngOnDestroy() {
        if (this.route$) this.route$.unsubscribe();
    }
}

Config:

export const routes = [
    ...
    { path : 'Person/:id', component : ...},
    ...
];

Also, @RouteConfig is deprecated.

like image 106
Kamil Myśliwiec Avatar answered Sep 28 '22 01:09

Kamil Myśliwiec