Search code examples
javascriptangularroutes

Angular 6 passing in parameters into URL


So I have an angular app that currently has a route such "urlname/stockdata". I would like to be able to pass in a stock symbol into that url such as "urlname/stockdata/AAPL". My app is making a call to a third party API with that symbol. Do you guys have any advice on how I can do that. Any help is appreciated. Thanks


Solution

  • You can declare a route with parameters like this:

    export const routes: Routes = [
      { path: 'urlname/stockdata/:id', component: MyComp}
    ];
    

    Create a link in the template:

    <a [routerLink]="['/urlname/stockdata', id]">MyLink</a>
    

    Or navigate from the .ts:

     this.router.navigate(['/urlname/stockdata', id]);
    

    Then you can read it with:

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