2

I want to create anchor in my angular page but it doesn't work and I don't know why.

My html component :

<h1 id="choose_package">Step 1 : choose a package</h1>
<div>Some elements</div>
<a [href]="choose_package">test</a>

But it return me null and go to 404 page.

Edit (now I can scroll but it's not done little by little):

this.router.events.pipe(filter(e => e instanceof Scroll)).subscribe((e: any) => {
    if (e.position) {
      this.viewportScroller.scrollToPosition(e.position);
    } else if (e.anchor) {
      this.viewportScroller.scrollToAnchor(e.anchor);
    } else {
      this.viewportScroller.scrollToPosition([0, 0]);
    }
  ;
});
user10863293
  • 770
  • 4
  • 11
  • 32

2 Answers2

0

Anchor Scrolling are disabled by default at v6.1.0. Enable the anchor scrolling inside the route configuration

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

Then use fragment

<h1 id="choose_package">Step 1 : choose a package for your license</h1>
<div>Some elements</div>
<a [fragment]="choose_package">test</a>
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
0

use Fragment to do it.

<h1 id="choose_package">
Step 1 : choose a package for your license
</h1>
<div>Some elements</div>
<a [fragment]="choose_package">test</a>

It will redirect to "choose_package" on the same page.

You also need to define in your rootModule the anchorScrolling

...
@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      anchorScrolling: 'enabled',
    })
  ]
})
...
Yoarthur
  • 909
  • 9
  • 20
  • Hi, I have the error : Unable to assign type '{anchorScrolling: string; scrollPositionRestoration: string; } 'to type' ExtraOptions'. An object literal can only specify known properties, and 'anchorScrolling' does not exist in the 'ExtraOptions' type. – user10863293 Jan 14 '19 at 13:55