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

Abhijit Mondal Abhi
  • 1,364
  • 4
  • 15
  • 34
  • Did you import `NavController`? – Joseph Webber Aug 13 '18 at 18:00
  • Ofcourse! `import { MenuController, NavController } from '../../../../node_modules/@ionic/angular';` – Abhijit Mondal Abhi Aug 13 '18 at 18:01
  • You should just be able to use `import { MenuController, NavController } from 'ionic-angular';`. What error/s are you getting? – Joseph Webber Aug 13 '18 at 18:05
  • `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. @JosephWebber – Abhijit Mondal Abhi Aug 13 '18 at 18:11
  • 2
    Checking out the [Ionic 4 API](https://beta.ionicframework.com/docs/api/), I couldn't find any info on `NavController`, only `Nav`. Try changing `NavController` to `Nav` and see if that works. – Joseph Webber Aug 13 '18 at 18:18
  • 1
    `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! – Abhijit Mondal Abhi Aug 13 '18 at 18:41
  • `import { MenuController, NavController } from '@ionic/angular';`. About back button you need to add it yourself now : https://github.com/ionic-team/ionic/blob/master/angular/BREAKING.md#back-button – Jeremy Belolo Jan 26 '19 at 19:59
  • use below method: this.navController.navigateRoot('/cmspagedetail/'+id); – Kamlesh Apr 06 '19 at 09:58

9 Answers9

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/

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() {
  }

}
Mihir Patel
  • 416
  • 5
  • 13
  • fyi, more on how to use Router in ionic v4 https://blog.ionicframework.com/navigating-the-change-with-ionic-4-and-angular-router/ – cevaris Mar 17 '19 at 14:29
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

  • 2
    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. – taylorthurlow Jan 23 '19 at 00:56
4

Try (in ionic 4)

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

instead of (in ionic 3)

import { NavController } from 'ionic-angular'
bunny
  • 1,316
  • 2
  • 13
  • 22
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

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>
Abhijit Mondal Abhi
  • 1,364
  • 4
  • 15
  • 34
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/

Cesar Devesa
  • 990
  • 6
  • 14
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>
Narm
  • 10,677
  • 5
  • 41
  • 54
Dart Vadar
  • 11
  • 1
-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)
        })
    })
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
Raj Gond
  • 11
  • 2
  • 1
    Please, can you extend your answer with more detailed explanation? This will be very useful for understanding. Thank you! – vezunchik Apr 16 '19 at 07:30