0

In Angular 2 (currently 2.0.0-rc.6), routerLink is used as a directive to indicate a path we wish to follow in our routing, e.g. in response to clicking a link.

However, in the documentation both of the following are used:

  • routerLink
  • [routerLink]

I don't understand when I should use which. The Basics / Template Syntax page discusses how square brackets are used for, among other things, setting a property of a directive. To me, that sounds like I should use square brackets in this case but the documentation shows otherwise.

When I initially pondered this question, I thought it might have something to do with the use of a plain string, e.g. routerLink="/heroes" versus something more complex and/or dynamic such as a link parameters array, e.g. [routerLink]="['/hero', hero.id]". However, the following two direct quotes from the documentation show that that is not the answer:

From Developer Guide / Routing & Navigation (about half way down the page):

<a routerLink="/crisis-center/admin" routerLinkActive="active">Crisis Admin</a>

From API Reference / RouterLink:

<a [routerLink]="/user/bob">link to user component</a>

The data-binding source on the right side of the equals sign in each of those examples has the same format, i.e. is just a string.

So, when do I use which?

asked Sep 7, 2016 at 2:01
3
  • This provides a good overview of the binding modes, and the syntax to use for each. Commented Sep 7, 2016 at 2:15
  • Yes that page does provide a good overview of some relevant general principles, and in fact I link to that page in my question. I don't think, however, that it answers my specific question. I suppose my question could be re-phrased as "When should I not use square brackets for routerLink?" which, I believe, is not addressed by that page, at least not in a clear, obvious way. Commented Sep 7, 2016 at 2:39
  • You could always try both, and see if there's a difference in behavior. Commented Sep 7, 2016 at 3:08

1 Answer 1

1

Whenever something is in square brackets the content gets evaluated. Probably the reference was wrong because <a [routerLink]="/user/bob"> won't work because the code /user/bob has syntax error, actually it's a malformed Regex.

I checked the reference, now it has <a [routerLink]="['/user/bob']"> and <a routerLink="/user/bob">, both of them are correct.

answered Jun 7, 2017 at 10:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.