Reputation: 1451
My question is very similar to this but it's not working for me. I already asked the person who post it but I got no reply, so here I go. I basically want to generate links from a function:
generator(linkFor, linkPath){
if (linkFor == 'msg'){
// now linkPath is something like 2/4
// and the route to read the message is message/view/2/4
return 'message/view/' + linkPath
}
}
and the if conditions do go on. From template I do:
<a href="javascript:void(0)" [routerLink]="generator(data.type, data.source)">{{data.source_name}}</a>
Now the link is being generated but adds ():
message/view/(2/4)
and thus, it can't be found. Where are the braces coming from?
Upvotes: 1
Views: 2197
Reputation: 3618
There is performance issue with [routerLink] above logic. What are the drawbacks let me come first
Try this :
<a href="javascript:void(0)" [routerLink]="generator(data.type, data.source)">Test</a>
generator(linkFor, linkPath){
console.log('Generate URL for me');
}
Note: Check now how many times the console is printed, Reason is this async call and called and slows the application performance
so here is another way we can generate links from a function
<a href="javascript:void(0)" (click)="generator(data.type, data.source)">Test</a>
import { Router } from '@angular/router';
constructor(private _router: Router)
generator(linkFor, linkPath){
console.log('Generate URL for me');
if (linkFor == 'msg'){
this._router.navigate(['message/view/' + linkPath])
}
}
Note: Now check console log is printed only once which is a better performance way to implement generate links from a function.
In short [routerLink] async call hits the function infinity way even when the user action is not performed. The (click) will work only according to user actions.
Upvotes: 1
Reputation: 12978
generator(linkFor, linkPath){
if (linkFor == 'msg'){
return ['message', 'view', linkPath]
}
return null;
}
Upvotes: 1