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

Moh*_*mad 5 routing angular

I want to an anchor link to jump to specific section in the same page using id hashtag. here is my html:

<div class="nav-container">
  <ul class="nav text-center">
    <li class="active">
      <a href="#account-services">Services</a>
    </li>
    <li>
      <a [routerLink]="['//account/'+account.account_id]" fragment="account-about">About</a>
    </li>
    <li>
      <a href="#account-gallery">Gallery</a>
    </li>
    <li>
      <a href="#account-reviews">Reviews</a>
    </li>
  </ul>
</div>
<div class="account-details">
  <div id="account-services">
    <h1>services</h1>
  </div>
  <div id="account-about">
    <h1>About Us</h1>
  </div>
  <div id="account-store">
    <h1>Store</h1>
  </div>
  <div id="account-gallery">
    <h1>Gallery</h1>
  </div>
  <div id="account-reviews">
    <h1>Reviews</h1>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

ts component:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-account-individual',
  templateUrl: './account-individual.component.html',
  styleUrls: ['./account-individual.component.css']
})
export class AccountIndividualComponent implements OnInit {

  private fragment: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
  }

  ngAfterViewInit(): void {
    try {
      document.querySelector('#' + this.fragment).scrollIntoView();
    } catch (e) {
      console.log(e);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Ali*_*mal 11

像您一样使用片段并将其分配给点击事件:

在你的模板中

<a fragment="account-about" (click)="navigateToSection('account-about')>About</a>

<div id="account-about">...</div>
Run Code Online (Sandbox Code Playgroud)

在您的组件中

public navigateToSection(section: string) {
      window.location.hash = '';
      window.location.hash = section;
}
Run Code Online (Sandbox Code Playgroud)


Pro*_*lma 6

这是针对 Angular 13 的,其中 ngx-page-scroll 当前无法工作。

import { ViewportScroller } from '@angular/common';

constructor(private viewportScroller: ViewportScroller) {}

public onClick(elementId: string): void { 
  this.viewportScroller.scrollToAnchor(elementId);
}
Run Code Online (Sandbox Code Playgroud)

在 component.ts 文件中添加上部部分。对于 html 文件 -

     <a (click)="onClick('about')" >About</a>
     <div id="about">....</div>
Run Code Online (Sandbox Code Playgroud)


Bri*_*ani 3

安装此软件包ng2-page-scroll

之后导入您的app.module.ts

    import {Ng2PageScrollModule} from 'ng2-page-scroll';
    
    @NgModule({
        imports: [
            /* Other imports here */
            Ng2PageScrollModule
            ]
    })

   export class AppModule {
   }
Run Code Online (Sandbox Code Playgroud)

并在你的组件 html 中进行测试

<a pageScroll href="#home">Testing</a>
<div id="home">
Run Code Online (Sandbox Code Playgroud)