如何(访问/进入)页面的特定部分?

时间:2019-06-12 11:47:58

标签: angular typescript

我需要访问主页中包含的共享组件。 我已经在页脚之前添加了此内容,但是在顶部,我有一个按钮,当单击该按钮时,我要将用户定向到主页的这一部分。

      <button
        class="popular__button"
        routerLink="/popular-categories"
        id="home__middle-box-button"
        style="cursor: pointer;">
        Popular categories
      </button>
.........
......
<app-listing>
</app-listing>
<app-footer>
</app-footer>

我尝试使用传统方式,但是当我尝试访问它时,它会带我进入一个新页面,而我不希望那样。 谁能帮我任何技巧,如何访问页面的这一部分。

我希望可以访问的组件如下所示:

<app-browse-grid [categories]="categories$" class="popular">
  <h2>{{ 'category.popular-categories' | translate }}</h2>
</app-browse-grid>
<div fxLayout="column wrap" fxLayout.lt-sm="column" fxLayoutGap="32px" fxLayoutAlign="space-evenly center">
  <div class="button" fxFlex.sm="calc(100%)">
    <button class="catalog__button"  routerLink="/browse">
      All categories
    </button>
  </div>
</div>

3 个答案:

答案 0 :(得分:1)

您可以将片段与routerLink一起使用。 routerLink doc

    <button
        routerLink="/popular-categories"
        fragment="ELEMENT_ID_TO_NAVIGATE"
    >
      Popular categories
      </button>


<div id="ELEMENT_ID_TO_NAVIGATE">this is the element i want to navigate<div>

编辑: 要使其工作,需要在路由器模块配置中启用锚滚动

RouterModule.forRoot(routes, {anchorScrolling: 'enabled'})

答案 1 :(得分:1)

另一种方法是添加(click)="yourFunction()",该函数看起来像

yourFunction(){
    this.router.navigateByUrl('/popular-categories');
}

您需要像这样的构造函数(专用路由器:路由器)将其初始化,并确保您这样导入路由器:

import { Router } from '@angular/router';

答案 2 :(得分:0)

我在此问题的答案中找到了解决方案之一: here

 like this: 

<button (click)="scroll(target)"></button>
<div #target>Your target</div>
and then in ts component:

scroll(el: HTMLElement) {
    el.scrollIntoView();
}

在尝试了很多东西之后,这项工作对我来说便是