Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Generate the route link using functions/ Dynamically generate the routerLink

Tags:

angular

router

I want to create a route link dynamically.

I have the html loaded with the page however, i need to use an id in the URL which is available much later.

HTML :

<a href="javascript:void(0)" routerLink="cartoonBoxUrl()" routerLinkActive="active">Add Content to Cartoon Box</a>

The link in this routelink contains the id of the cartoon box(/carton-box/1). This id is available after the page loads. Therefore i need a way to create a route link to include this id.

So i believe we can do something like : routerLink="'cartoon-box/' + id" but i was hoping to link routerlink to a component function

like image 601
Bhumi Singhal Avatar asked Dec 08 '22 20:12

Bhumi Singhal


2 Answers

Without [] Angular doesn't evaluate the expression and just uses cartoonBoxUrl() as literal string.

<a href="javascript:void(0)" [routerLink]="cartoonBoxUrl()" routerLinkActive="active">Add Content to Cartoon Box</a>
like image 57
Günter Zöchbauer Avatar answered Dec 10 '22 08:12

Günter Zöchbauer


<a href="javascript:void(0)" (click)=cartoonBoxUrl()>Add Content to Cartoon Box</a>

in your ts component.ts file do

import {Router} from "@angular/router";
public ID: any;
constructor(private router: Router){}
cartoonBoxUrl(){
 this.ID = Your LinkId;
 this.router.navigate(['YourRouteLink/', this.ID]);

}
like image 36
Manish Avatar answered Dec 10 '22 10:12

Manish