Home > Enterprise >  How to navigate to a route with query param but without showing ? and = in the URL
How to navigate to a route with query param but without showing ? and = in the URL

Time:01-07

I've never implemented routing in Angular. my requirement is to navigate to a details page when an icon is clicked from parent component. Here is my code:

product.component.ts

  // method called when the corresponding pencil/edit icon is clicked
  loadSingleRecord() {
    this._router.navigate(['products/electronic/billing/'], {
      queryParams: { id: 12 }, // let it be id 12 for sometime
    });
  }

product-routing.module.ts

const routes: Routes = [
  ...
  {
    path: 'electronic/billing/:id',
    component: BillingSingleRecordComponent,
  },
  ...
];

@NgModule({
  imports: [RouterModule.forChild(routes), HttpClientModule],
  exports: [RouterModule],
})
export class ProductsRoutingModule {}

This logic is working fine:

localhost:4205/products/electronic/billing/record?id=29

but I dont want to show ?id=29. Can it be simple like this: localhost:4205/products/electronic/billing/record/29. Please help.

I forgot to meantion that on reaching the details component I want the id also:

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe((params) => {
      let id = params['id'];
      console.log(id); // OUTPUT undefined
    });

CodePudding user response:

The :id in the path electronic/billing/:id is not a queryParam, but rather a route parameter (also known as path variable). Check out this tutorial for more info

When you navigate, you should use

this._router.navigate(['products/electronic/billing', id]);

if you want to read this in your component, you can use

ngOnInit(): void {
    this.activatedRoute.params.subscribe((params) => {
        let id = params['id'];
        console.log(id);
    });
}
  • Related