a blog for those who code

Wednesday 6 March 2019

When to use [routerLink] or routerLink in Angular


RouterLink allows you to link specific routes in your app, i.e. you can navigate to a different route.

For example :

<a routerLink="/myRoute">Take me to My Route</a>

will take you to http://localhost:4200/myRoute when clicked.

Now the main difference between using routerLink and [routerLink] is that in routerLink you can only specify static link whereas using [routerLink] you can use dynamic values to generate the link where you will pass an array of path segments.

When we use square brackets, i.e. [routerLink] it means that we are passing a bindable property which can be defined in our class and it can also be changed from the class which makes it dynamic but in the case of without brackets, we are passing a string and thus we cannot change it.

<a routerLink="/myRoute">Take me to My Route</a>
<a [routerLink]="myRoute">Take me to My Route</a>

export class myComponent {
  public myRoute = "/myRoute";
  updatingMyRoute() {
    this.myRoute = "/changedMyRoute";
  }
}

In the above code the value of myRoute is changed when we used [routerLink] this will be useful in the case when you have to permanently change some route in your application, thus you do not have to manually update it everwhere but can do at one place and you are done.

No comments:

Post a Comment