Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

anchor href vs angular routerlink

Tags:

I am trying to use anchor tag with href in my Angular 7 app. When I click on the link the url changes in the browser but the page doesn't get navigated to. It works if I put target="_self" so this works

<a href="/abcd" target="_self">Abcd</a> 

but this does not work only the url changes in the browser but nothing happens

<a href="/abcd">Abcd</a> 

where as if I use Angular routing and use RouterLink it works.

<a routerLink="/abcd" routerLinkActive="active">Abcd</a> 

Can anyone explain the behaviour please.

like image 780
tangokhi Avatar asked Sep 24 '19 13:09

tangokhi


People also ask

What is routerLink in Angular?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.

Can I use routerLink on Div?

Yes it can be attached to div tag, your route is probably wrong try add / in front of route.

What does routerLink directive do?

Linking Routes in HTMLTo add links to one of the routes, use the routerLink directive in HTML. This directive accepts an array. The first parameter is the name of the route, and the second parameter is the parameters that you want to pass with the route.

Can I use routerLink on button?

If you need logic to occur before you go to a route you can import the Router Module and use it as such. I'm unsure of the best practice but I would say that it is fine to use routerLink and (click) in the same button as long as you do not interfere with the navigation. Manually navigation via this. router.


1 Answers

Href is the basic attribute provided by Html to navigate through pages which reloads the page on click.

routerLink is the attribute provided by angular to navigate to different components without reloading the page.

Major difference between both is that href kills the state of the current page where routerLink doesnt lose the state of the page.

For Eg. if an input text box is present in the page, the routerLink will retains its value after navigation.The routerLink can be considered as the custom attribute of href in angular by overriding some of the features like Page reloading

like image 62
Thaks Avatar answered Sep 25 '22 16:09

Thaks