Search code examples
angular5routerlinkangular-routerlink

Customize routerLink in Angular 5


In my application I am using routerLink to create my link as per according to parameter passed in routerLink.

<a [routerLink]="['/home/global/userprofile',UserId]">

Above code generate links with the userId provided, but I want to customize angular routerLink so that I can check if UserId is valid or not, if valid I will return the converted href link throught this and if not I will return blank or null url.

I can not use any other directive approach or pipe factories as I am using this routerLink code in several places in my project so I just not want to go and change each and every where that code is writtern. Can anyone guide me in this? I just need concept, I can write code for the idea.

If required, I can explain it more if any queries for this.


Solution

  • Instead of using routerLink directive, I suggest You to use a programmatical redirection in your component class, like this:

    HTML component file

    <a (click)="goToUserProfile(UserId)">Some link</a>
    

    TS Component class:

    import { Router } from '@angular/router';
    
    constructor(private router: Router) {}
    
    goToUserProfile(userId: number) {
        if (/* userId verification*/) {
            this.router.navigate(['/home/global/userprofile', userId]);
        }
        // do nothing
    }
    

    Otherwise, you can use a router guard, here are some useful links:

    Hope it helps.