Ouen A
Ouen A

Reputation: 179

Dislay id and name in a route path - Angular

I would like to change a URL path in a website path from http://localhost:4200/viewbrand/1 to http://localhost:4200/viewbrand/1/soap ie. to include a name after the ID.

The existing code in routing module.ts file:

{ path: 'viewbrand/:id', component: LocalbrandsComponent },

Existing code in HTML file:

 <a class="tile-link" href="/viewbrand/{{brand.id}}"></a>
                  

I would think the change would be as follows to the module.ts file and the HTML file.

{ path: 'viewbrand/:id'/:brand.name, component: LocalbrandsComponent }

<a class="tile-link" href="/viewbrand/{{brand.id}}/{{brand.name}}"></a>

Does this follow the correct logic? It does not work.

Upvotes: 0

Views: 2764

Answers (2)

Chris Hamilton
Chris Hamilton

Reputation: 10984

I intially thought you want to redirect from the old url to the new one, but I think you're just trying to edit the url, in which case you haven't put the full path inside quotations.

{ path: 'viewbrand/:id/:name', component: LocalbrandsComponent }
<a class="tile-link" href="/viewbrand/{{brand.id}}/{{brand.name}}"></a>

If that's the case, I'm a bit concerned your IDE didn't let you know about that. Anyways, the redirect solution is below as well.


This is doable, but you need an intermediary component to extract the name and then redirect to the new route.

{ path: 'viewbrand/:id', component: RedirectComponent },
{ path: 'viewbrand/:id/:name', component: LocalbrandsComponent },
export class RedirectComponent {
  constructor(private router: Router, private route: ActivatedRoute) {}

  getName(id: string) {
    return 'name-for-' + id;
  }

  ngOnInit(): void {
    const id = this.route.snapshot.params['id'];
    const name = this.getName(id);
    this.router.navigate(['viewbrand', id, name]);
  }
}

Upvotes: 2

Birhan Nega
Birhan Nega

Reputation: 681

You can't use values that will be dynamically rendered in route.

Upvotes: 0

Related Questions