Search code examples
angularrouterangular2-changedetection

Angular2 Router V3 and Menu selection


I would like my menu to show the current route by applying an 'active' class on the menuItem (Like in Ng1) base on the current route.

@Component({
  moduleId: module.id,
  selector: 'main-menu',
  directives: [
    ROUTER_DIRECTIVES,
  ],
  template: '
<paper-button #menu1 [data]="['/app/collection']" [routerLink]="['/app/collection']" [ngClass]="{active: isActive(menu1.data)}">My Collection</paper-button>
<paper-button #menu2 [data]="['/app/book/find']" [routerLink]="['/app/book/find']" [ngClass]="{active: isActive(menu2.data)}">Browse Books</paper-button>'
})
export class MainMenuComponent {

  public current:string;

  constructor(public router:Router, private changeDetector:ChangeDetectorRef) {
    this.router.events.subscribe((e)=> {
      this.current = e.url;
    });
  }

  ngOnInit() {
    this.changeDetector.detectChanges();
  }

  isActive(data) {
    if (data) {
      return this.current == data[0];
    }
  }
}

So this works, but there are 2 issues that I would like some help to solve:

1) I need to call the this.changeDetector.detectChanges(); Otherwise the active class is not applied on initial load of the page.(I don't understand why this is no working out of the box...)

2) In regards to the template I haven't found a way not to repeat my self in the routerLink. I would like to be able to pass a ref to my data, like menu2.data but it doesn't work...

Any help/advice would be appreciated thanks


Solution

  • In the new router you can define what class should be added to a routerLink when the route is active:

    <a [routerLink]="['/app/collection']" [routerLinkActive]="['active']">Home</a>