176

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>
Claies
  • 22,124
  • 4
  • 53
  • 77
Liska Liskor
  • 2,831
  • 4
  • 17
  • 22

7 Answers7

354

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 1

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 (No "'/url?" since Angular 6, when a Route in RouterModule exists) -

 <button [routerLink]="'url'"> Button Label</button>
ib.
  • 27,830
  • 11
  • 80
  • 100
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • 2
    can i send some data with it ? – Anuj Mar 12 '18 at 07:58
  • 20
    Not sure if things have changed since this was written, but as of October 2018, it seems you can just put the `[routerLink]` attribute directly on the ` – Mark Adelsberger Oct 24 '18 at 13:52
  • So which way is cleanest? Is it better not to expose the route in the markup but keep it instead in the typescript file, or is the 'new' way with `[routerLink]` in the template the way to go? – Rin and Len Jan 25 '19 at 09:45
  • it's up to you, IMO, there is no logic to hide your markup in the template as you are going to navigate to the user can see in the next page. Rest both are same i guess – Pardeep Jain Jan 25 '19 at 18:51
  • 1
    At the first level `html file` where the component gonna be loaded has to have `` tag. please refer https://angular.io/api/router/RouterOutlet#description for more details. – Tharusha Feb 04 '19 at 13:29
  • How about something that would look like `` ? But it gives me an error. Is there a correct syntax for this ? – Stephane Apr 04 '19 at 09:29
  • I'm finding in my application, that `` tries to navigate to: `/mypath,99`, instead of: `/mypath/99` where model.SomeVal == 99. I've tried all manner of combinations in the `routerLink` attribute value and nothing works as expected when you need to navigate to a parameterized route. – Ken Hadden Dec 06 '19 at 00:09
  • There must be some other problem with your code, as you posted code seems to be fine, Can you create a stackblize example for me to debug easily? – Pardeep Jain Dec 06 '19 at 11:14
  • No need to use brackets here as we bind to a static String. Just use `routerLink="/url"`... – mmey Aug 14 '20 at 20:44
  • yeah, but earlier it has to be used with static strings as well. – Pardeep Jain Aug 17 '20 at 06:22
51

You can use routerLink in the following manner,

<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">

or use <button [routerLink]="['./url']"> in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471

the other methods are also correct but they create a dependency on the component file.

Hope your concern is resolved.

ADyson
  • 57,178
  • 14
  • 51
  • 63
Ronit Oommen
  • 3,040
  • 4
  • 17
  • 25
  • 1
    @Ronit Why not just: – Andy King Apr 02 '18 at 06:41
  • 1
    @AndyKing Because he is using an expression (an array as a value), `foo="boo"` is like `[foo]="'boo'"`. Maybe you want to read https://stackoverflow.com/questions/43633452/when-to-use-square-brackets-in-directives-inputs-and-when-not – PhoneixS May 02 '18 at 11:27
  • 1
    I prefer this answer – HungNM2 Jul 13 '18 at 14:31
14
 <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.navigate(['/user']);
};
Aniket
  • 552
  • 4
  • 13
  • I did something similar like this at first (using router.navigate), then looked for other ideas, and now use routerLink as mentioned in other answers. I wonder which is better, or if it matters... – Scott Nov 01 '18 at 23:13
8

There were many comments and answers which suggested to use routerLink - in different ways. I think, the following is the best way nowadays:

A relative simple link:

<button [routerLink]="/Service/Sign_in">Add Customer</button>

also possible with an array like

<button [routerLink]="['/Service', serviceId, 'Sign_in']">Add Customer</button>

to get a link to /Service/2102/Sign_in where serviceID is 2102.


If you have query parameters use:

<button [routerLink]="/Service/Sign_in" [queryParams]="{mode:'red'}">Add Customer</button>

and you receive a link to /Service/Sign_in?mode=red.


If your current url already has params (eg /Service/foo?status=bar), you can add keep and add additional params with:

<button [routerLink]="/Service/Sign_in" [queryParams]="{mode:'red'}" queryParamsHandling="merge">Add Customer</button>

which should give you a link to /Service/foo?status=bar&mode=red.

Or you can even preserve the existing ones (if some exist, eg if you are on /Service/foo?mode=blue) with:

<button [routerLink]="/Service/Sign_in" [queryParams]="{mode:'red'}" queryParamsHandling="preserve">Add Customer</button>

and you receive a link to /Service/Sign_in?mode=blue.


Some more modes to preserve the history or work with fragments are explained here: https://angular.io/api/router/RouterLink

Datz
  • 3,156
  • 3
  • 22
  • 50
4

It is important that you decorate the router link and link with square brackets as follows:

<a [routerLink]="['/service']"> <button class="btn btn-info"> link to other page </button></a>

Where "/service" in this case is the path url specified in the routing component.

Mwiza
  • 7,780
  • 3
  • 46
  • 42
3

There is one significant difference that no one seem to mention.

If you use [routerLink] on the button directly, or you navigate in your .ts file using router, the HTML will not show your button as a link.

This has several implications:

  • it will not show the user the link that they are about to navigate to (oh hover, on the bottom left screen of the browser)

URL Preview

  • they will not be able to open the link in new tab (using right click or control/command click
  • this also has SEO implications as crawling engines would not recognise it as a link

In order to give the user the best experience possible I would strongly encourage you to use the format of wrapping your button in a tag:

<a [routerLink]="'/home'"><button>Home</button></a>
SDekov
  • 9,276
  • 1
  • 20
  • 50
2

Having the router link on the button seems to work fine for me:

<button class="nav-link" routerLink="/" (click)="hideMenu()">
     <i class="fa fa-home"></i> 
     <span>Home</span>
</button>
Rob
  • 6,819
  • 17
  • 71
  • 131