ussefshahid
ussefshahid

Reputation: 158

Angular4 - routerLink with typescript

I have worked with routerLink and it works very well :

      <a routerLink="inscription" class="btn btn-default">Inscription</a>
      <a routerLink="login" class="btn btn-default">Se connecter</a>

I am trying now to deal with routerLink inside the typescript file. Exactly, when i click on a button, i call a function inside this function i want to call routerLink how could i do it? and if is calling it will reload the page or it will work exactly the same as the routerLink above ?

Upvotes: 10

Views: 28426

Answers (4)

EMorain
EMorain

Reputation: 1

From what I have learned, routerLink is simply a wrapper for the Router method navigateByUrl(...). I was using routerLink so that I can update a secondary outlet. This worked for me:

this.router.navigateByUrl(this.router.createUrlTree(["/<parent>", {outlets: {'<outlet_name>': ['<outlet_path>']}}]))

To describe in words, router.navigateByUrl seems to prevent the page reload, but it only accepts a pure url, no params (to my understanding). I use router.createUrlTree(...) to generate a "pure" url from the additional outlet/query/etc params I need the url to have. Maybe it would read better like this:

generatedUrl = this.router.createUrlTree(["/<parent>",  {outlets: {'<outlet_name>': ['<outlet_path>']}}])

router.navigateByUrl(generatedUrl)

Upvotes: 0

Aaron Hodgson
Aaron Hodgson

Reputation: 11

Please note that though the URL in the browser is not case sensitive, Router.navigate is.

Correct: this.router.navigate(['/products']);.

Incorrect: this.router.navigate(['/Products']);

Upvotes: 1

Jorawar Singh
Jorawar Singh

Reputation: 7621

try this

<a javascript:void(0) routerLink="inscription" class="btn btn-default">Inscription</a>

Upvotes: 2

DeborahK
DeborahK

Reputation: 60518

In code, you use .navigate instead:

this.router.navigate(['/products']);

You pass it the same parameter as you do the routerLink.

enter image description here

Upvotes: 42

Related Questions