Search code examples
angularangular-router

Routing in angular by insert parameter in URL


Suppose I have a component A which routes on localhost:4200/A I want to render A also when I pass parameters after A, like localhost:4200/A/xyz without any button click.

Simply if I hit the URL localhost:4200/A/xyz it should render component A here xyz is dynamic it may be changing.


Solution

  • You can add a route definition with a parameter like this:

    {
            path: 'A/:id', component: AComponent
        },
    

    Then in AComponent

    import { ActivatedRoute } from '@angular/router';
    @Component({
      selector: 'app-a',
      templateUrl: './a.component.html',
      styleUrls: ['./a.component.css']
    })
    export class AComponent{
      data: string;
      constructor(private activatedRoute: ActivatedRoute) {
         this.loadData();
      }
    
      loadData() {
        this.activatedRoute.paramMap.subscribe(params => {
          this.data= params.get('id');
    
        });
      }