Search code examples
angularangular-router

Angular 4 location.path to navigate between components


I have recently started a project with angular 4 an typescripts. All is going well until one point:

I have a need to create routing principles. For this I have created routing in My App.Module.ts:

RouterModule.forRoot([
      {path: '', component: HomeComponent },
      {path: 'thanks', component: ThanksComponent} //, canActivate: [AuthGuard]

    ])

In angular js, in order to pass from one route to another we used routeConfig and then just used in controller:

$location.path("/roue");

In order to navigate.

My big idea is to navigate between components just like I used navigation in angular js. How can I navigate between components in Angular 4?


Solution

  • @Sajeetharan almost got it.

    import the Router with

    import { Router } from '@angular/router';
    

    Inject it in your component

    constructor(private router: Router) {}
    

    Now you have several ways to call it

    this.router.navigate(['thanks']); // Array of routes
    this.router.navigateByUrl('/thanks'); // Absolute path
    this.router.navigate(['thanks', 1]); // route corresponding to thanks/1, useful for params