Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic2 - check if page is active

Tags:

angular

ionic2

How can I check if a ionic2 page is active?

For example I want to hide a button if a page is active:

<button primary [hidden]="isActive('actualPageName')">
     Should be hidden
</button>
like image 499
muetzerich Avatar asked Apr 19 '16 16:04

muetzerich


3 Answers

IONIC 2 & 3: Because of the uglification you cannot use pagename for production.

I check the active page by looking if the last page on the controller stack is of the instance of the page:

import { NavController } from 'ionic-angular';
import { myPage } from '../../pages/my/my';
...
constructor(public navCtrl: NavController) {}
...
let active = this.navCtrl.last().instance instanceof MyPage;

IONIC 4: Routing is changed. This looks like the new way:

import { Router } from '@angular/router';
...
constructor(public router: Router) {}
...
let active =  this.router.isActive('mypage', false)
like image 138
Paul Avatar answered Oct 21 '22 12:10

Paul


You can retrieve the active page and check its name:

public isActive(pageName: string): boolean {
   return this.navCtrl.getActive().name === pageName);
}

UPDATE

In the comments you can see some users that claim this solution is not working for them due to the Uglify process. It sounds reasonable, but I still found the solution seems to work. I've compiled an APK with this code using this command:

ionic cordova build android --prod --release

During compilation you can see:

...
[13:00:41]  uglifyjs started ... 
[13:00:43]  sass finished in 2.45 s 
[13:00:43]  cleancss started ... 
[13:00:46]  cleancss finished in 3.05 s 
[13:00:57]  uglifyjs finished in 16.27 s
...

Then, when I run that app in the Android emulator I got the right page name using this.navCtrl.getActive().name.

I must say I've not tested it with a signed application in a real device.

May be Android or the emulator is not affected, may be the problem described by those users is solved in recent releases, may be I'm doing something wrong. Because I don't know the response to this questions I maintain my answer but I've added this info. Please, if you know more about this comment it instead of just ignoring or donwvoting this answer. If this answer is proven wrong I'll happily modify or delete it.

like image 35
sanzante Avatar answered Oct 21 '22 11:10

sanzante


Update to the @sanzante answers. You can retrieve an active page and check it's name as follows.

public isActive(pageName: string): boolean {
   return this.navCtrl.getActive().id === pageName);
}

It will work for the --prod build version as well.

ionic cordova build android --prod --release

like image 1
user3033174 Avatar answered Oct 21 '22 11:10

user3033174