How to get current page from Navigation in ionic 2 - ionic2

I am new to Ionic2, and I am trying to build dynamic tabs based on current menu selection. I am just wondering how can I get current page using navigation controller.
...
export class TabsPage {
constructor(navParams: NavParams,navCtrl:NavController) {
//here I want to get current page
}
}
...
From api documentation I feel getActiveChildNav() or getActive() will give me the current page, but I have no knowledge on ViewController/Nav.
Any help will be appreciated. Thanks in advance.

Full example:
import { NavController } from 'ionic-angular';
export class Page {
constructor(public navCtrl:NavController) {
}
(...)
getActivePage(): string {
return this.navCtrl.getActive().name;
}
}
Method to get current page name:
this.navCtrl.getActive().name
More details here

OMG! This Really Helped mate, Tons of Thanks! #Deivide
I have been stuck for 1 Month, Your answer saved me. :)
Thanks!
if(navCtrl.getActive().component === DashboardPage){
this.showAlert();
}
else
{
this.navCtrl.pop();
}

My team had to build a separate custom shared menu bar, that would be shared and displayed with most pages. From inside of this menu component.ts calling this.navCtrl.getActive().name returns the previous page name. We were able to get the current page name in this case using:
ngAfterViewInit() {
let currentPage = this.app.getActiveNav().getViews()[0].name;
console.log('current page is: ', currentPage);
}

this.navCtrl.getActive().name != TheComponent.name
or
this.navCtrl.getActive().component !== TheComponent
is also possible

navCtrl.getActive() seems to be buggy in certain circumstances, because it returns the wrong ViewController if .setRoot was just used or if .pop was just used, whereas navCtrl.getActive() seems to return the correct ViewController if .push was used.
Use the viewController emitted by the viewDidEnter Observable instead of using navCtrl.getActive() to get the correct active ViewController, like so:
navCtrl.viewDidEnter.subscribe(item=> {
const viewController = item as ViewController;
const n = viewController.name;
console.log('active page: ' + n);
});
I have tested this inside the viewDidEnter subscription, don't know about other lifecycle events ..

Old post. But this is how I get current page name both in dev and prod
this.appCtrl.getActiveNav().getActive().id

Instead of
...
...
//In debug mode alert value is 'HomePage'
//In production/ signed apk alert value is 'n'
alert(activeView.component.name);
if (activeView.component.name === 'HomePage') {
...
...
Use this
...
...
//In debug mode alert value is 'HomePage'
//In production/ signed apk alert value is 'HomePage'
alert(activeView.id);
if (activeView.id === 'HomePage') {
...
...
Source Link

You can use getActive to get active ViewController. The ViewController has component and its the instance of current view. The issue is the comparsion method. I've came up to solution with settings some field like id:string for all my Page components and then compare them. Unfortunately simple checking function name so getActive().component.name will break after minification.

Related

Ember active link

I have a route where I want to make a sibling route's link-to's active as well. I have tried using current-when in the link-to, but it's not working for me.
my routes are as follows
//projects
//projects/:project_id
//projects/:project_id/user/:user_id
When I navigate to //projects/:project_id route, the right link is set to active. I want the same link to be active on the //projects/:project_id/users/:user_id route.
My link-to in the parent //projects hbs template is
{{#link-to "projects.project" item.projectID current-when="projects.user" tagName="tr"}}
What am I doing wrong here?
UPDATE
I was able to get it to initially work when the route is rendered by using an edited version of #ykaragol's helper function and link-to...
{{#link-to "projects.project" item.projectName active=(calculate-active 'projects.user projects.project' item.projectName) tagName="tr"}}
compute(params, hash){
var pathname = window.location.pathname.split('/');
var pathProj = pathname[2];
var currRoute = this.get('currentRouteName');
var routes = params[0].split(' ');
if( ($.inArray( currRoute, routes) > -1) && (pathProj == params[1]) ){
return true;
}
return false;
}
But it's not updating when I click on a different project...
If routes don't have dynamic segments, it works as described in docs. I've tested it within this twiddle.
But I couldn't make it work while using dynamic segment. Please check this twiddle. I suspect this maybe a bug. You can ask this question in slack.
By the way, as a workaround, you can pass a boolean to the currentWhen property (as mentioned in docs). So you can write a helper or a computed property to calculate it with a regex.
Updated:
As a second workaround, you can handle active property of link-to by yourself. Try this twiddle.

Ionic2: invalid page component: ProjectInfoPage

export class ProjectDetail {
page: string;
}
the page info contained in json, like this:
{
"data":[
{
page: "PageInfoPage"
},
{
page: "PageInfoPage1"
}
]
}
I parse info from this json,then saved in Array.
when execute this.nav.push(pd.page),throw exception as title described.I don't know how to convert 'string' to 'component'.
============================================================
I use the method like Angular 2 - Resolve Component Factory with a string described. This is my code:
itemClick(pd: ProjectDetail) {
var factories = Array.from(this.resolver['_factories'].keys());
var factoryClass = <Type<any>>factories.find((x: any) => x.name === pd.page);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);
if (this.componentRef) {
this.componentRef.destroy();
}
this.componentRef = compRef;
this.nav.push(compRef, {
item: pd,
pid: this.project.pid
});
}
it still does not work.Thank you for your answer.
At last,I solved it with a stupid method.As I create a map like this:
componentRegistry = {
'ProjectInfoPage': ProjectInfoPage
};
And then push like this:
this.nav.push(this.componentRegistry[pd.page], {
item: pd,
pid: this.project.pid
});
Normally, you have to import the actual component class for the page that you want to navigate to and then push that class onto the stack. By default, there is no way built into ionic2 to navigate via string references. I had the same problem today where I wanted to be able to navigate using strings rather than pushing the component class on the stack.
Check out the following link from the ionic forums on how to accomplish this. Look at the last two responses to the thread, which include how to solve this problem from beta stages and then an updated answer for how to do so with ionic 2.2.0. Although I'm pretty sure the same solution will work for all versions of ionic 2 since final release.
https://forum.ionicframework.com/t/ionic2-navigation-circular-depencies/41123/5

Remove a view from the back history - Ionic2

Anyone knows how to remove a view from the back history (or navigation stack) in ionic2?
In Ionic 1 I solved this with
this.$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
Would be really useful, for example, to fully remove the login page of my application from the history once a successfully login was performed.
Just not showing the back button isn't enough in such case, since Android terminals got their own physical back button on the devices.
I tried, after my login function returned a successful promise and before pushing the next page in the stack:
this.navController.pop();
or
this.navController.remove(this.viewCtrl.index);
but unfortunately both weren't successful :(
obrejacatalin on the https://forum.ionicframework.com/t/solved-disable-back-in-ionic2/57457 found the solution
this.nav.push(TabsPage).then(() => {
const index = this.nav.getActive().index;
this.nav.remove(0, index);
});
so I guess it's important to push the next page first, wait for the promise answer and then remove the current view
To remove one backview you need to use startIndex and count of pages to remove from stack.
this.navCtrl.push(NextPage)
.then(() => {
const startIndex = this.navCtrl.getActive().index - 1;
this.navCtrl.remove(startIndex, 1);
});
See this document for more options like removeView(viewController):
https://ionicframework.com/docs/v2/api/navigation/NavController/#remove
I got the same issue with Ionic 3.
So, only two steps to reset history:
// ...
constructor(public navCtrl: NavController) { }
// ...
this.navCtrl.setRoot(NewPageWithoutPrev);
this.navCtrl.popToRoot();
// ...
Links:
https://ionicframework.com/docs/api/navigation/NavController/#setRoot
https://ionicframework.com/docs/api/navigation/NavController/#popToRoot

emberjs action event.target is undefined

Here's a link to a jsfiddle: http://jsfiddle.net/Qt972/
When you run the fiddle you'll see a name and a button to make the "person" say hello. This works fine, however the "event" is undefined.
An even simpeler case also fails:
http://jsfiddle.net/CCg2K/1/
Does anyone know how I can fix this issue?
When you do a console.log(arguments) inside your action callback you can see that there are actually 3 parameters passed. The first one is the view, the second is the event and the third is the context.
You can rewrite your edit action like this:
edit: function(view, event, context) {
var target = event.target;
...
}
UPDATE: since commit 657a2664 - available in release 0.9.6 I guess - only a single event parameter is passed which has the view and context as properties. So if you want to access those you have to do the following:
edit: function(event) {
var view = event.view;
var context = event.context;
...
}

ValueChanging event on Infragistics WebDataGrid

Does anyone have an idea why this doesn't work or a workaround?
I'm trying to use the ValueChanging event from inside an EditorProvider
I have defined an EditProvider
<ig:TextEditorProvider ID="tepPercent">
<EditorControl HorizontalAlign="Right" ClientEvents-ValueChanging="validatePercent4Decimals"></EditorControl>
</ig:TextEditorProvider>
And a javascript handler
function validatePercent4Decimals(sender, args) {
var oldfieldvalue = args.get_oldValue();
var newfieldvalue = args.get_value();
if (isNaN(newfieldvalue)) {
args.set_value(oldfieldvalue);
args.set_cancel(true);
}
}
I've debugged it and can see it is running, and if I enter 34r, the inNan tests true and the set_value and set_cancel are called. But the value on the grid does not change from the 34r...
What's going on?
From this post on the Infragistics forums I believe that you have a numeric column. If this is the case then you should use a NumbericEditorProvider instead. There are more details on the available editor provides in the Infragistics help:
http://help.infragistics.com/NetAdvantage/ASPNET/2011.1?page=WebDataGrid_Editor_Providers.html