【问题标题】:angular: how to make link to jump for certain section in the same page角度:如何使链接跳转到同一页面中的某些部分
【发布时间】:2018-06-24 22:53:05
【问题描述】:

我想要一个锚链接以使用 id 标签跳转到同一页面中的特定部分。这是我的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 组件:

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

【问题讨论】:

  • 你能控制 this.fragment 吗?
  • @ShaileshLadumor 是的,结果是href 属性值
  • 这个问题的解决方案已经回答here

标签: angular routing


【解决方案1】:

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

在您的模板中

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

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

在你的组件中

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

【讨论】:

    【解决方案2】:

    安装这个包
    ng2-page-scroll

    在您的app.module.ts导入后

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

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

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

    【讨论】:

    【解决方案3】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 2019-12-28
      • 2018-12-12
      • 2011-03-16
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      相关资源
      最近更新 更多