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

12,994

Solution 1

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>

Solution 2

<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]);

}
Share:
12,994
Bhumi Singhal
Author by

Bhumi Singhal

Updated on June 05, 2022

Comments

  • Bhumi Singhal
    Bhumi Singhal almost 2 years

    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

  • Force444
    Force444 over 6 years
    Doing it this way, routerLinkActive gets lost. Gunters answer is the correct way to do it.
  • rmcsharry
    rmcsharry about 6 years
    This is useful it you want to open a link to some other place outside of your Angular app.
  • OPV
    OPV almost 6 years
    How to use routerLinkActive in this case?