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

余生颓废 提交于 2019-11-28 06:18:56

问题


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>

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);
    }
  }
}

回答1:


install this package
ng2-page-scroll

after 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">



回答2:


Use fragment as you did and bind to a click event like so:

in the html

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

<div id="account-about">...</div>

in the ts

public navigateToSection(section: string) {
      window.location.hash = '';
      window.location.hash = section;
}



回答3:


try this

this.route.fragment.subscribe(fragment => { 
                      setTimeout(() => {
                            this.scrollTo(fragment);
                        }, 300);
     });


来源:https://stackoverflow.com/questions/48277721/angular-how-to-make-link-to-jump-for-certain-section-in-the-same-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!