Trouble arises when trying to navigate to a new page from ion-tabs within Ionic 2

I recently developed a chat application that redirects users to a tabs page upon login.

 <ion-tabs tabsPlacement="top" color="header" tabsHighlight=true>
  <ion-tab [root]="tab1" tabTitle="Chats" tabIcon="chatbubbles"></ion-tab>
  <ion-tab [root]="tab2" tabTitle="Groups" tabIcon="contacts"></ion-tab>
  <ion-tab [root]="tab3" tabTitle="Profile" tabIcon="contact"></ion-tab>
</ion-tabs>

https://i.sstatic.net/k8tRk.png

  1. After logging in, I tried to retrieve the active page from the tabs using

    console.log(this.navCtrl.getActive().name);
    . However, it returns undefined. Can someone explain why?

  2. When I navigate to a new page by clicking the app icon on the header with

    this.navCtrl.push('FriendsPage');
    , the current active page displays the previous page name "ChatPage" instead of "FriendsPage" https://i.sstatic.net/nWG38.png

Edit: Added backbutton action

      this.platform.registerBackButtonAction(() => {
    let activePortal = this.ionicApp._loadingPortal.getActive() ||
      this.ionicApp._modalPortal.getActive() ||
      this.ionicApp._toastPortal.getActive() ||
      this.ionicApp._overlayPortal.getActive();
    if (activePortal) {
      activePortal.dismiss();
    } else {
      if (this.nav.canGoBack()) {
        this.nav.pop();
      } else {
        if (this.nav.getActive().name === "LoginPage"||this.nav.getActive().name === "SignupPage") {
          this.platform.exitApp();
        }else {
          this.generic.showAlertConfirm("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");
        }
      }
    }
  })

In my scenario, when a user goes to the FriendsPage from the tabs and presses the hardware back button, an alert message pops up instead of the view simply popping as expected.

this.generic.showAlertConfirm("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");

I would appreciate any assistance in resolving this issue.

Warm Regards,

Anand Raj

Answer №1

I encountered a similar issue to yours and have yet to uncover the reason behind it. However, I did discover a solution to retrieve the correct page name.

Within app.component.ts, insert the following code:

import { App } from 'ionic-angular';
constructor(private app: App){
}
ngAfterViewInit() { 
    this.app.getActiveNav().viewWillEnter.subscribe(event => {
      console.log("current page", event.id);  <== This is what you require
    })
}

Now you can access the page name in every viewWillEnter event without needing to add code to each individual page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a placeholder class for the Form Builder group component within an Angular application

Currently, I am in the process of creating numerous new forms. For instance: constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ 'name': ['', Validators.required], 'email&apo ...

Tips for utilizing method overload in TypeScript with a basic object?

Looking at this code snippet: type Foo = { func(a: string): void; func(b: number, a: string): void; } const f: Foo = { func(b, a) { // ??? } } An error is encountered stating: Type '(b: number, a: string) => void' is not assign ...

Error code TS7053 occurs when an element implicitly has an 'any' type because a string expression cannot be used to index an empty object

I have implemented a code snippet that sorts items into groups based on their first character. For example, if the array of item looks like this: {name: 'Foo'} {name: 'Bar'} {name: 'Baz'} The expected result should be: B: ...

Creating a declaration of an array containing key value pairs in Typescript

Feeling lost with the syntax provided below: constructor(controls: {[key: string]: AbstractControl}, optionals?: {[key: string]: boolean}, validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn) I'm curious about the type of the controls (first ...

Angular does not display a loading indicator in the header

When handling service calls, I have implemented a loading indicator to provide feedback to the user. However, it appears that this indicator is not effectively preventing users from interacting with header items before the loading process is complete. My ...

What is the process of creating a for loop in FindById and then sending a response with Mongoose?

Is there a way to get all the data in one go after the for loop is completed and store it in the database? The code currently receives user object id values through req.body. If the server receives 3 id values, it should respond with 3 sets of data to th ...

Firestore data displaying as null values

Recently, I encountered CORS errors while polling the weather every 30 seconds in my program. Upon investigating, I discovered that the city and country were being interpreted as undefined. To fetch user data from my users' table, I utilize an Axios ...

"Attempting to verify a JSON Web Token using a promise that returns an object not compatible with the specified

Learning about Typescript has been quite a challenge for me, especially when it comes to using the correct syntax. I have implemented a promise to retrieve decoded content from jwt.verify - jsonwebtoken. It is functioning as intended and providing an obje ...

Angular 6 Error: Unable to access property 'e4b7...f' as it is undefined

I'm encountering an issue while trying to initialize an object based on a TypeScript interface. Even though I am assigning a value, I still receive an error stating that the property is undefined. interface ITableData { domainObjectName: string; ...

When interacting with the iframe in an Ionic3 app, it suddenly crashes

Greetings! I have integrated a flipping book URL inside an iframe: <ng-container> <iframe [src]="eUrl" id="flipping_book_iframe" frameborder="0" allowfullscreen="allowfullsc ...

The compiler does not recognize the TSConfig option 'lib' - please review and correct

I have inherited an angular 1 project written in typescript version 1.8.10. However, I am encountering compilation issues with the following error message: Unknown compiler option 'lib' If I remove the "lib" line, a cascade of other errors suc ...

Steps to successfully pass a reference from a parent component to a child component that utilizes TouchableOpacity in React Native

I am facing an issue with passing a transitioning ref from a parent Transitioning view to a child component: const transition = ( <Transition.Together> <Transition.In type="fade" durationMs={300} /> <Transition.Change /&g ...

Enhance your Next.js application by including the 'style' attribute to an element within an event listener

I am currently trying to add styles to a DOM element in Next.js using TypeScript. However, I keep getting the error message "Property 'style' does not exist on type 'Element'" in Visual Studio Code. I have been unable to find an answer ...

Creating void functions in TypeScript

I encountered a section of code within a custom component that is proving to be quite puzzling for me to comprehend. public onTouch: () => void = () => {} The function onTouch is being assigned by the private method registerOnTouch(fn: any) { ...

Google Chrome - Automatically scroll to the bottom of the list when new elements are added in *ngFor loop

I have a basic webpage showcasing a list of videos. Towards the bottom of the page, there is a button labeled "Load more". When a user clicks on this button, an HTTP request is triggered to add more data to the existing array of videos. Here is a simplifi ...

Angular - Automatically create thumbnails for uploaded images and videos

I am working on an Angular application that allows users to upload files. My goal is to create thumbnail images for uploaded images and videos without saving them locally. Instead, I plan to pass them along with the original file data to another API. Howev ...

What is the reason behind the warning about DOM element appearing when custom props are passed to a styled element in MUI?

Working on a project using mui v5 in React with Typescript. I am currently trying to style a div element but keep encountering this error message in the console: "Warning: React does not recognize the openFilterDrawer prop on a DOM element. If you in ...

Updating webdriver-manager can sometimes result in a "spawn Unknown system error -86" message. This error

(Angular). webdriver-manager 12.1.7 is causing issues specifically on Intel-based Macs. When running e2e tests, the error message "spawn Unknown system error -86" is encountered. The bug has been addressed in webdriver-manager 12.1.8, however, I am facing ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

What is the best way to execute the Angular build output (dist folder, artifact)?

After creating an Angular build for my app using the command: $ ng build I uploaded the result to my remote server: https://i.sstatic.net/9O7fZ.png On the server, I have also installed the necessary node version and Angular CLI. However, when I att ...