3
votes

Is there a way to conditionally hide a router-link in Angular2?

For example, I have the following code;

<li><a [routerLink]="['RegisterUser']">Register User</a></li>

I want to hide the link when the user is logged in.

On my component, I use the @CanActivate decorator to determine if the route can be activated, but this doesn't hide the link itself.

@CanActivate(() => hasValidToken())

I could use the *ngIf structural directive with the hasValidToken() method (which returns a boolean) but this seems heavy handed and a bit dirty.

<li><a [routerLink]="['RegisterUser']" *ngIf="!hasValidToken()">Register User</a></li>

Is there a cleaner way to approach this?

Thanks

1

1 Answers

3
votes

How I did it, which makes it easier if you ever want to add more routes in the future is create a service with an observable that watches for a loggedIn event.

Then I just use ngOnChanges and when someone logs in, I append the other menu items to my menu and do an *ngFor loop over my [routerLink]'s.

@Component({
  selector: 'my-cmp',
  template: `<li *ngFor="#prop in myProps><a [routerLink]="[prop]">Register User</a></li>`
})
class MyComponent implements OnChanges {
  @Input() LoggedIn: any;
  constructor(){
    myProps = ['About_Me', 'Not_Logged_In_Menu_Item'];
  }
  ngOnChanges(changes: {[propName: string]: SimpleChange}) {
    myProps.push(changes['LoggedIn'].currentValue);
    console.log('ngOnChanges - myProps = ' + changes['myProps'].currentValue);
  }
}

The only reason I would do it this way though is if you feel down the line you will have to change additional menu items for logged in users. This was for an Auth and Auth application, where some users had more accesses than other users.