Ionic 5: set ion-item “Active” with routerLink

The native angular directive [routerLinkActive] does not fit well with <ion-item/> component: routerLinkActive works with element’s classes, ion-item change its appearance using the [color] attribute.

This custom directive solves this problem.

import {Directive, Input, OnDestroy, OnInit} from '@angular/core';
import {IonItem} from "@ionic/angular";
import {NavigationEnd, Router, RouterLink} from "@angular/router";
import {filter, map, tap} from "rxjs/operators";
import {Subscription} from "rxjs";


@Directive({
  selector: '[ionRouterLinkActive]'
})
export class IonRouterLinkActiveDirective implements OnInit, OnDestroy {


  private handler: Subscription;

  constructor(private router: Router, private ionItem: IonItem, private rl: RouterLink) {
  }

  ngOnInit(): void {

    this.handler = this.router.events.pipe(
      filter(x => {
        return x instanceof NavigationEnd
      }),
      map(() => {       
        return this.rl && this.router.isActive(this.rl.urlTree, false);
      }),
      tap(isActive => {
        this.ionItem.color = isActive ? "secondary" : null;
      })
    ).subscribe();
  }

  ngOnDestroy() {
    this.handler.unsubscribe();
  }

}
<ion-item routerLink="sample" ionRouterLinkActive>
</ion-item>