What is the difference between [routerLink]
and routerLink
? How should you use each one?
Difference between [routerLink] and routerLink
227.4k views Asked by Eslam Tahoon AtThere are 4 answers
Assume that you have
const appRoutes: Routes = [
{path: 'recipes', component: RecipesComponent }
];
<a routerLink ="recipes">Recipes</a>
It means that clicking Recipes hyperlink will jump to http://localhost:4200/recipes
Assume that the parameter is 1
<a [routerLink] = "['/recipes', parameter]"></a>
It means that passing dynamic parameter, 1 to the link, then you navigate to http://localhost:4200/recipes/1
Router Link
routerLink with brackets and none - simple explanation.
The difference between routerLink= and [routerLink] is mostly like relative and absolute path.
Similar to a href you may want to navigate to ./about.html or https://your-site.com/about.html.
When you use without brackets then you navigate relative and without params;
my-app.com/dashboard/client
"jumping" from my-app.com/dashboard to my-app.com/dashboard/client
<a routerLink="client/{{ client.id }}" .... rest the same
When you use routerLink with brackets then you execute app to navigate absolute and you can add params how is the puzzle of your new link
first of all it will not include the "jump" from dashboard/ to dashboard/client/client-id and bring you data of client/client-id which is more helpful for EDIT CLIENT
<a [routerLink]="['/client', client.id]" ... rest the same
The absolute way or brackets routerLink require additional set up of you components and app.routing.module.ts
The code without error will "tell you more/what is the purpose of []" when you make the test. Just check this with or without []. Than you may experiments with selectors which - as mention above - helps with dynamics routing.
See whats the routerLink construct
You'll see this in all the directives:
When you use brackets, it means you're passing a bindable property (a variable).
So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below:
But with variables, you have the opportunity to make it dynamic right?
Where as without brackets you're passing string only and you can't change it, it's hard coded and it'll be like that throughout your app.
UPDATE :
The other speciality about using brackets specifically for routerLink is that you can pass dynamic query parameters to the link you're navigating to:
So adding a new variable
Updating the [routerLink]
When you want to click on this link, it would become: