Is there a similar way to push navigation in Angular 6 like we do in Ionic 3?

Viewed 2113

I'm trying to navigate to a different page in Angular 6.

In Ionic we do it by calling navCtrl.push('ExamplePage');

In Angular 6 I understand they are routes but I'm not being able to navigate using a button like:

app.component.html

<button (click)='goToExamplePage()'>ExamplePage</button>

<router-outlet></router-outlet>

app.component.ts

import {Router} from '@angular/router';
constructor(private router: Router)

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

app.module.ts

 import { RouterModule, Routes } from '@angular/router';

 const appRoutes: Routes = [
  {path: '', component: AppComponent},
  { path: 'example',     component: ExampleComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    ExampleComponent
  ],
  imports: [
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
   ...
  ],
  bootstrap: [AppComponent],
  exports: [
    RouterModule
  ]
})

It simply doesn't do anything. Any help please?

1 Answers

For those still arriving here with questions. This is the correct way of manually navigating to a route.

The problem above is that AppComponent is the bootstrap component as well as the root route ('/') component. The reasons you are not seeing an endless nested template is because Angular only uses the outer <router-outlet/>.

Here is a basic manual navigation example https://stackblitz.com/edit/angular-ivy-pykkry. Edit the app and add the app component as the root route as see the effect.

Related