1 Mar 2022

Angular: HTML anchor tag with #idref issue


I am working on an Angular 10 project, where I am not using location hash strategy as I want to use HTML anchor tag with #idref concept. So my ng serve link is containing path like, //localhost:4500/dashboard/wallet.

<li routerLinkActive="active">
 <a [routerLink]="['/dashboard/wallet']">Wallet</a>
 <ul class="child-link-sub">
 <a href="#depoWallet">Deposit Wallet</a>
 <a href="#withdrawalWallet">Withdrawal Wallet</a>
 <a href="#trnWallet">Transaction</a>

When I click on Deposit wallet, it should scroll down to bottom where I put id = “depoWallet”; But it is not working anymore!

I went through with this git thread, which should solve the issue using below line,

<a [routerLink]="['/dashboard/wallet/']" fragment="depoWallet" >Deposit Wallet</a>

When I click the anchor tag, It appends #depoWallet at the end of the URL but it doesn't scroll to the top of the browser.

Does anyone know the proper solution?



1 Mar 2022

Best Answer

best answer

If you are using Angular 6+ then this approach will work for you.

#Approach 1: Angular 6 Introduced anchorScrolling property, which scrolls to #idref element. (No hash-location-strategy)

const routerOption: ExtraOptions = {

 anchorScrolling: 'enabled', //If you enabled it, it will allow you to scroll to the element by #idref

 useHash: false, // You already marked it false

 // ...other options if applicable

Don't forget to import your RouterModule with above options.

RouterModule.forRoot(MY_APP_ROUTES, routerOption)

#Approach 2: Using scrollIntoView property using template reference variable.

Add your HTML code as below

<button (click)="scrollToIdRef(target)"></button>
<div #target>Your target</div>

Add your CSS code as below

scrollToIdRef(element): void {

 element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});

This approach will work with Hash Location strategy too.

I recommend 2nd approach. You can make a common method and use it in all the component html-ts.




1 Mar 2022

Yes 2nd approach worked for me, thanks for giving your time.

© 2024 Copyrights reserved for