Angular Js

How to create fragment in url (Jump-To-Anchor)

How to create fragment in url (Jump-To-Anchor)

How to create fragment in url in Angular?

This Article helps you to Understand, How to create fragment in url (Jump-To-Anchor)?


Router Options
To make our fragment router property function, we will develop a configuration that will include router options.


app-routing.module.ts
set ExtraOptions above

  • scrollPositionRestoration: on change of router url the position of the screen will set to the top.
  • anchorScrolling : When set to ‘enabled’, scrolls to the anchor element when the URL has a fragment. Anchor scrolling is disabled by default.
  • scrollOffset: Configures the scroll offset the router will use when scrolling to an element.



import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes, ExtraOptions } from '@angular/router';
import { AppComponent } from '../app.component';
import { HomeComponent } from '../home/home.component';
import { HelloComponent } from '../hello.component';

const routerOptions: ExtraOptions = {
  scrollPositionRestoration: 'enabled',
  anchorScrolling: 'enabled',
  scrollOffset: [0, 64],
};

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
  }, 

  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  }
 ]
@NgModule({
  imports: [CommonModule, RouterModule.forRoot(routes, routerOptions)],
  exports: [RouterModule]
})
export class AppRoutingModule { }




Create A Fragment URL

The fragment will include the section's ID, which will be used in the anchor tag.


import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  ids: Array<String> = ['one', 'two', 'three', 'four']
}



Anchor tags in Template

<div class="links">
  <ul>
    <li *ngFor="let link of ids">
      <a [routerLink]='"."' [fragment]="link">{{link}}</a>
    </li>
  </ul>
</div>

All sections with id attribute will be as follow


<section>
  <div class="section" *ngFor="let link of ids" [attr.id]='link' >
    <h1>{{link}}</h1>
    <div class="content">
      <!--  YOUR CONTENT GOES HERE  -->
    </div>
  </div>
</section>



Use Fragment in Navigation
Use Fragment inside Dynamic Link


<button class="btn btn- primary" (click)="onLoadServer(1)">
  Load Server
</button>


onLoadServer(id: number) {
    this.router.navigate(["/servers", id, "edit"], {
      queryParams: { allowEdit: "1" },
      fragment: "one"
    });
}

.



Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram