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?

  • This provides a good overview of the binding modes, and the syntax to use for each. – Robert Harvey Sep 7 '16 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. – Andrew Willems Sep 7 '16 at 2:39
  • You could always try both, and see if there's a difference in behavior. – Robert Harvey Sep 7 '16 at 3:08
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.