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>
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)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With