Home > Net >  Angular ver. 14.0.2, How to create anchors that redirect to certains blocks of the page?
Angular ver. 14.0.2, How to create anchors that redirect to certains blocks of the page?

Time:06-22

I'm currently using Angular for a few weeks for a small project and I wanted to add an anchor in my app.

So normally in order to add an anchor without using any framework, you'd create a block with an ID

<div id="top"> then you'd add an anchor tag <a href="#"> with the href attribute that would be equal to the ID of the block of the page we want to redirect the to.

ex:

<div id="top">...</div>

<a href="#top">...</a>

When we click on the link, it scrolls up to the page* to the block we defined the ID with.

*if we add in the CSS of the html or body tag scroll-behavior: smooth;

The issue is that when I add that inside my Angular template, it redirects me to the URL with the name of the ID on the href attribute!

If I take the previous example, here's what would happen:

localhost:4200/login → (click to the link) → localhost:4200/#top

Strangely it treats it as if it was a router link attribute

So I'm wondering how we could add an anchor in Angular

CodePudding user response:

So I found a solution! (thanks to @Benjamin Looi for giving me the link to a relevant post)

So actually Angular has an issue with anchor tags when we want the user to another part of the same page

The solution is to use routerOptions of type extra options in the appRoutingModule and add in some options, here's the code:

const routes: Routes = [...];

const routerOptions: ExtraOptions = {
  useHash: false,
  anchorScrolling: 'enabled',
  onSameUrlNavigation: 'reload' //Must have if you want to be able to use the anchor more than once
};

@NgModule({
  imports: [RouterModule.forRoot(routes, routerOptions)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Then in the template, we have to add the anchor of the block we want to redirect the user in the attributes fragment with the name of the ID and routerLink with the page you're in (otherwise it will redirect to "/")

ex:

<a routerLink="/login" fragment="top"></a>

Now it will successfully redirect to the top of the page!

CodePudding user response:

May be this might help

HTML code :

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

Ts code :

     scrollToElement($element): void {
        console.log($element);
        $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});

  }

got it from this

Using HTML anchor link #id in Angular 6

  • Related