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";

  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 =
      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;

  ngOnDestroy() {

<ion-item routerLink="sample" ionRouterLinkActive>