Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anchor fragments in Angular 6

Tags:

angular

I am trying to do something as simple as making anchor links that jump to a link on the same page. There is surprisingly only very limited documentation but I found following:

Using anchor link #id in Angular 6

@machado comment recommends following which seems like the correct approach:

const routerOptions: ExtraOptions = {
  useHash: false,
  anchorScrolling: 'enabled',
  // ...any other options you'd like to use
};


// Then just import your RouterModule with these options

RouterModule.forRoot(MY_APP_ROUTES, routerOptions)

However I haven't found any documentation on how to make the links. Following dosen't work:

My link:

<a href="#{{group.name}}">{{group.name}}</a> 

My anchor:

<h2 id="{{group.name}}">{{group.name}}</h2>
like image 560
Thomas Segato Avatar asked Sep 16 '25 21:09

Thomas Segato


1 Answers

If you need to do this on HTML template, just need to do

<h1 [attr.id]='link'>{{link}}</h1>

<a [routerLink]='"."' [fragment]="link">{{link}}</a>

Don't forget add options to your App Router

RouterModule.forRoot(routes, {
  scrollPositionRestoration: 'enabled',
  anchorScrolling: 'enabled',
  scrollOffset: [0, 25], // cool option, or ideal option when you have a fixed header on top.
});

Check this example about anchors links with fragment.

like image 56
pablorsk Avatar answered Sep 20 '25 11:09

pablorsk