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

删除回忆录丶 提交于 2019-12-23 12:29:20

问题


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


回答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>



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

}


来源:https://stackoverflow.com/questions/40544937/angular-2-generate-the-route-link-using-functions-dynamically-generate-the-rou

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!