Navigate to another page with a button in angular 2

Liska Liskor picture Liska Liskor · Jan 2, 2017 · Viewed 338.8k times · Source

I am trying to navigate to a another page by clicking a button but it fails to work. What could be the problem. I am now learning angular 2 and it's a bit tough for me now.

//Routes/Path in a folder call AdminBoard

export const AdminRoutes: Routes =[

  {
    path: 'dashboard',

    component: AdminComponent,
    children: [
      {path: '', redirectTo: 'Home'},
      {path: 'Home', component: HomeComponent},
      {path: 'Service', component: ServiceComponent},
      {path: 'Service/Sign_in', component:CustomerComponent}

    ]

  }

];

//Button is also in a different folder. Click button to navigate to this page           {path: 'Service/Sign_in', component:CustomerComponent}

  <button class="btn btn-success pull-right" ><a routerLink="/Service/Sign_in"> Add Customer</a></button>

Answer

Pardeep Jain picture Pardeep Jain · Jan 2, 2017

Use it like this, should work:

 <a routerLink="/Service/Sign_in"><button class="btn btn-success pull-right" > Add Customer</button></a>

You can also use router.navigateByUrl('..') like this:

<button type="button" class="btn btn-primary-outline pull-right" (click)="btnClick();"><i class="fa fa-plus"></i> Add</button>    

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

btnClick= function () {
        this.router.navigateByUrl('/user');
};

Update

You have to inject Router in the constructor like this:

constructor(private router: Router) { }

only then you are able to use this.router. Remember also to import RouterModule in your module.

Update 2

Now, After Angular v4 you can directly add routerLink attribute on the button (As mentioned by @mark in comment section) like below -

 <button [routerLink]="'/url'"> Button Label</button>