At work the other day we had this super strange bug where a certain page was breaking – seemingly at random.
Upon further investigation, we were able to find a set of steps to reproduce the issue and upon even further investigation, we were able to find the root of the issue.
Turns out using
ion-tab together in Ionic is bad news waiting to happen.
Let’s talk briefly about what each of these things are. Firstly,
ng-if is an Angular directive that will show, or not show, elements based upon an expression. For example:
<h5 ng-if="false">The Phantom Menace is better than The Force Awakens.</h5>
The above would not show because, in addition to being completely untrue,
ng-if is set to false. If you were to set
ng-if to true (although for that statement, I’m not sure why you would) the element would show.
This isn’t only limited to
ng-if can also contain an expression – something that is either truthy or falsy.
If at this point you’re thinking that this sounds really similar to
ng-show, well, you’re right. There is a key difference though.
ng-show will show or hide an element based upon an expression.
ng-if on the other hand completely removes the element from the DOM. Remember that, because there’s a pop quiz coming up.
Alright, so really briefly, Ionic allows you to have a tabbed menu at the bottom of your app. That is done with
ion-tab. But what if you want to show or hide a tab based upon certain criteria? You might think you could use
ng-class? Well, it turns out that the way
ion-tab was written, you can’t actually use
ng-hide? Nope, those don’t seem to work either.
ng-if however will show/hide your tab based upon criteria. You can check that out on my demo here.
But if you pay close attention to the demo, something about the ‘chats’ tab doesn’t seem quite right, does it? Why might that be? Well, remember when I said
ng-if completely removes elements from the DOM?
Bingo! Something about removing the element and then forcing it back in causes some issues with the way things render.
Alright, so we’ve determined that
ng-if are all out of the question. But what about our tab? It still needs to be hidden, right?
It turns out our good friends at Ionic foresaw this issue coming up and built in a handy little option called
hidden. It could look like this:
<ion-tab title="Carmen's Awesome Tab" hidden="shouldIShowOrShouldIGo"> </ion-tab>
Based on whatever
shouldIShowOrShouldIGo equates to – be it truthy or falsy – will determine whether or not the tab shows. But without all this yanking stuff out of the DOM nonsense we are running into with
You can check out Ionic’s
ion-tab docs here.