Angular2 – When to Use Square Brackets Around routerLink

angularjsjavascriptroutingsyntaxtemplates

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?

Best Answer

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.