Hyperlinks in Ionic Checkbox Labels

September 20th 2019 Ionic 4+ Ionic 2/3

Including a hyperlink in a checkbox label is a common way to provide more information about the choice the user is making. Unfortunately, in Ionic such a hyperlink doesn't work out of the box because the whole label acts as toggle for the checkbox. There's an easy way to make it work, though.

Here's the markup we want to use:

<ion-item>
  <ion-label>Checkbox label <a (click)="moreInfo()">More info...</a></ion-label>
  <ion-checkbox color="dark" checked="true"></ion-checkbox>
</ion-item>

The checkbox label includes a hyperlink (anchor element) with a click handler to show more information in some way (e.g. by opening a pop-up or using the in-app browser to show a web page). However, when you tap on the hyperlink, the click handler is not invoked. The checkbox is toggled, instead.

Interestingly enough, the hyperlink in a label works just fine if there's no checkbox in the same ion-item. The reason for that is that in the case of a checkbox, Ionic puts another layer over the item to expand the checkbox hitbox across the full item and to show a nice visual effect when you tap it. As a side-effect, this prevents the click event to reach the hyperlink.

To fix the issue, the hyperlink needs to be raised above this extra layer. This can be done by using relative positioning and changing the hyperlink's z-index:

/* Ionic 4 */
.ion-activatable {
  ion-label {
    a {
      position: relative;
      z-index: 10;
    }
  }
}

I'm applying this style only to hyperlinks in labels which are placed inside an ion-item with the extra tappable layer. Based on my experience, such items have the ion-activatable class applied to them. This short CSS snippet is enough to get the hyperlink working as expected.

The above style works with Ionic 4. In Ionic 3, the same approach can be used, except that a different class is applied to the ion-item element:

/* Ionic 3 */
.item-checkbox {
  ion-label {
    a {
      position: relative;
      z-index: 10;
    }
  }
}

The solution is really easy and elegant once you know how to do it, isn't it?

Get notified when a new blog post is published (usually every Friday):

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Copyright
Creative Commons License