NavController doesn't work in Ionic 4
Asked Answered
B

9

35

I'm injecting NavController in my constructor as I want to push a page. But, below code doesn't work in Ionic 4. It was totally okay in Ionic 3.

Constructor

constructor(public menuCtrl: MenuController, public navCtrl: NavController) {
    this.menuCtrl.enable(true);
   }

Method

goToSecondPage()
  {
    this.navCtrl.push(list);
  }

Error

Basie answered 13/8, 2018 at 17:56 Comment(8)
Did you import NavController?Cockalorum
Ofcourse! import { MenuController, NavController } from '../../../../node_modules/@ionic/angular';Basie
You should just be able to use import { MenuController, NavController } from 'ionic-angular';. What error/s are you getting?Cockalorum
import { MenuController, NavController } from 'ionic-angular'; isn't work for me. Because, it can't find ionic-angular. I also searched Ionic 4 documentation. But, this is not clear. @JosephWebberBasie
Checking out the Ionic 4 API, I couldn't find any info on NavController, only Nav. Try changing NavController to Nav and see if that works.Cockalorum
this.navCtrl.goForward('/list'); it's work for Ionic 4! Ionic 4 suggests to use angular routing. But, now the problem is there is no back button in navbar when I go to the second page!Basie
import { MenuController, NavController } from '@ionic/angular';. About back button you need to add it yourself now : github.com/ionic-team/ionic/blob/master/angular/…Campstool
use below method: this.navController.navigateRoot('/cmspagedetail/'+id);Salimeter
T
54

Now, to complete the final step and implement those routes in our app-routing.module.ts file, they would look like this:

const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', loadChildren: './pages/home/home.module#HomeModule' },
{ path: 'products', loadChildren: './pages/products/products.module#ProductsModule'},
{ path: 'products/:id', loadChildren: './pages/product-detail/product-detail.module#ProductDetailModule' },
{ path: 'products/categories', loadChildren: './pages/product-categories/product-categories.
{ path: 'support', loadChildren: './pages/support/support.module#SupportModule' }
];

setRoot in html page

<ion-button href="/support" routerDirection="root">

or in class

this.navCtrl.navigateRoot('/support');

Push

<ion-button href="/products/12" routerDirection="forward">

or

this.navCtrl.navigateForward('/products/12');

Pop

<ion-button href="/products" routerDirection="backward">

or

<ion-back-button defaultHref="/products"></ion-back-button>

you can also navigate backwards programatically:

this.navCtrl.navigateBack('/products');

p/s: https://www.joshmorony.com/converting-ionic-3-push-pop-navigation-to-angular-routing-in-ionic-4/

Turner answered 24/10, 2018 at 7:33 Comment(0)
A
9

NavController as this is deprecated in IONIC 4.

Structure is like this.

     V3                 V4
/src/pages     ->   /src/app/pages
/src/models    ->   /src/app/models
/src/providers ->   /src/app/providers
  • You can use pages if you have pages directory.
  • You can use parameters if you want to pass it.

    this.router.navigate('/pages, { locs: this.locId }])');

Example: With Pages directory.

this.router.navigate(['/list'], { locs: this.locId }]);

Example: Without Pages directory and parameters.

this.router.navigate(['/list']);

This link is useful for the tabs. For more Info go through this link. [https://medium.com/modus-create-front-end-development/upgrading-an-ionic-3-application-to-ionic-4-eaf81a53cdea][1]


Extras:

After navigate to new page, we can get the locsId using this.route.snapshot.paramMap.get('locs') by importing private route: ActivatedRoute inside the current page constructor

Example:

export class ListPage implements OnInit {

  constructor(private route: ActivatedRoute) {
    console.log("this.route.snapshot.paramMap.get : ", this.route.snapshot.paramMap.get('locs'));
  }

  ngOnInit() {
  }

}
Atrioventricular answered 6/11, 2018 at 12:57 Comment(1)
fyi, more on how to use Router in ionic v4 blog.ionicframework.com/…Stifle
U
5
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
 ...
})
export class LoginComponent {
 constructor(private router: Router){}

    navigate(){
       this.router.navigate(['/detail'])
    }
}

for more info click here

Undistinguished answered 23/1, 2019 at 0:43 Comment(1)
Hi Edward, thanks for submitting an answer. While your answer is helpful, it might be more helpful if you included some information other than code that answers the original question. It's best to avoid just linking to documentation.Dotson
C
4

Try (in ionic 4)

import { NavController } from '@ionic/angular';

instead of (in ionic 3)

import { NavController } from 'ionic-angular'
Cnut answered 17/4, 2019 at 11:26 Comment(0)
S
2

first import navcontroller import { NavController, AlertController } from '@ionic/angular'; and now go forward also dont support it was best in ionic 3 this.nav.navigateForward('/ChatPage') supported in ionic 4 for but my sugesstion one should use angular routing

Squalene answered 2/2, 2019 at 16:29 Comment(0)
B
1
this.navCtrl.push(list);

It doesn't work in Ionic 4. Ionic 4 is based on Angular Routing. So, just use the following code, and write a route for this.

this.navCtrl.goForward('/list');

For back button in NavBar

Paste following code in <ion-toolbar> </ion-toolbar> for back button in the 2nd page.

<ion-buttons slot="start">
      <ion-back-button  defaultHref="home"></ion-back-button>
    </ion-buttons>
Basie answered 13/8, 2018 at 19:0 Comment(0)
S
1

IONIC 4 - Angular (ionic start appName --type=angular)

Physical Back Button and Back Button Menu

In the Target page (second page), do:

SecondPage TS

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import { Subscription } from 'rxjs';
    import { Platform } from '@ionic/angular';

    @Component({
      selector: 'app-second',
      templateUrl: './second.page.html',
      styleUrls: ['./second.page.scss'],
    })
    export class SecondPage implements OnInit, OnDestroy {

        inscBackAction: Subscription;
        element: HTMLElement;

        constructor(
          private router: Router, 
          public platform: Platform) {
        }

        ngOnInit() {    
          this.inscBackAction = this.platform.backButton.subscribe(() => {
            // Check this log in chrome: "chrome://inspect/#devices"
            console.log('Physical Back Button');                

            this.element = document.getElementById('backButton') as HTMLElement;
            this.element.click();
            // OR
            // this.router.navigate(['/anyPage']);

          }, error => {
            console.log('\n\nERROR:\n' + error.message + '\n\n');
          });
        }

        ngOnDestroy() {
          this.inscBackButton.unsubscribe();
        }
    }

SecondPage HTML

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
      <!-- Does not work with #backButton -->
      <ion-back-button id="backButton" defaultHref="/"></ion-back-button>
    </ion-buttons>
    <ion-title>
      Second
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding></ion-content>

_

P.S.:

May be necessary for menu links in HTML:

[routerDirection] = "'forward'"

Like in "app.component.html" on projects sidemenu

<ion-item [routerDirection]="'forward'" [routerLink]="[p.url]">

See More:https://beta.ionicframework.com/docs/api/buttons/

Scour answered 22/8, 2018 at 15:34 Comment(0)
L
1

You could just fix this by using "import { navController } from 'ionic-angular'" But that's gonna give you an error with Rxjs. So you might wanna do this...

In your app-routing.module.ts, make sure your pages and their modules are correctly specified in the path and loadChildren. Here's mine

const routes: Routes = [ { path: '', redirectTo: 'login', pathMatch: 'full' },

{ path: 'register', loadChildren: './register/register.module#RegisterPageModule' },
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' },
{ path: 'register', loadChildren: './register/register.module#RegisterPageModule' },
];

In my login.page.html, I used this to navigate to registerPage

<ion-button size="large" routerLink="/register" routerDirection="forward" expand="block" #btnregister fill="clear" color="primary">Register</ion-button>
Lollard answered 10/4, 2019 at 14:29 Comment(0)
K
-1
 this.deeplink.route({
          '/registration/:userid': RegistrationPage,
          '/registration': RegistrationPage,
      }).subscribe((match) => {  
        this.router.navigateByUrl(match.$link.path, match.$args)  
        console.log("Deeplink =>", match);

        }, err => {
          console.log("Deeplink Error=>", err)
          alert("Deeplink Error=>" + err)
        })
    })
Kirman answered 16/4, 2019 at 7:21 Comment(1)
Please, can you extend your answer with more detailed explanation? This will be very useful for understanding. Thank you!Cogon

© 2022 - 2024 — McMap. All rights reserved.