Using HTML Anchor Link #Id in Angular 6

Using HTML anchor link #id in Angular 6

Angular 6.1 comes with an option called anchorScrolling that lives in router module's ExtraOptions. As the anchorScrolling definition says:

Configures if the router should scroll to the element when the url has a fragment.

'disabled' -- does nothing (default).

'enabled' -- scrolls to the element. This option will be the default in the future.

Anchor scrolling does not happen on 'popstate'. Instead, we restore the position that we stored or scroll to the top.

You can use it like that:

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)

Anchor fragments in Angular 6

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.

angular: how to make link to jump for certain section in the same page

Install this package ng2-page-scroll

After that import in your app.module.ts

    import {Ng2PageScrollModule} from 'ng2-page-scroll';

@NgModule({
imports: [
/* Other imports here */
Ng2PageScrollModule
]
})

export class AppModule {
}

and test in your component html

<a pageScroll href="#home">Testing</a>
<div id="home">

Anchor in the same page

TherouterLink attribute is how Angular transite into pages, to connect to an anchor in your own page, use the old and cool <a href=#visit>

  <ion-card>
<ion-item class="activated">
<ion-icon name="camera" slot="start"></ion-icon>
<a href="#visit">
<ion-label>Pics</ion-label>
</a>
</ion-icon>
</ion-item>
</ion-card>

Another solution, to makes scroll smooth you can call an method on click at <ion-label (click)="scroll()">Pics</ion-label> and invoke

 scroll() {
var anchor = document.getElementById("visit");
anchor.scrollIntoView({block: "end", behavior: "smooth"});
}


Related Topics



Leave a reply



Submit