首页 > 解决方案 > 单页应用程序Angular 6中的组件路由

问题描述

我正在使用 Angular 6,我的项目中有 4 个组件。我想在一个页面中添加所有这些组件,并且我希望正确的菜单项处于活动状态,并且当我滚动到单个页面中的不同组件时,url 会更改为正确的路由。我一直在努力解决这个问题,非常感谢任何帮助。

这是我的 header.component.html

    <section class="module-small navbar-light">
<mdb-navbar  SideClass="navbar fixed-top navbar-custom navbar-expand-lg scrolling-navbar ie-nav" [containerInside]="false">
  <logo class="logo">
    <img src="./assets/images/phf-logo.png" />
  </logo>
  <links class="links">
    <ul class="navbar-nav mr-auto">
    </ul>
    <ul class="navbar-nav navbar-flex-icons">
      <li class="nav-item active waves-light" mdbRippleRadius [ngClass]="{'green-text': activeMenu=='about'}" routerLink="/about"
       (click)="scroll(about,'about')">
        <a class="nav-link">ABOUT<span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item waves-light" mdbRippleRadius [ngClass]="{'green-text': activeMenu=='features'}" routerLink="/features" (click)="scroll(features,'features')">
        <a class="nav-link">FEATURES</a>
      </li>
      <li class="nav-item waves-light" mdbRippleRadius [ngClass]="{'green-text': activeMenu=='management'}" routerLink="/management" (click)="scroll(management,'management')">
        <a class="nav-link">MANAGEMENT</a>
      </li>
      <li class="nav-item waves-light" mdbRippleRadius [ngClass]="{'green-text': activeMenu=='contact'}" routerLink="/contact"
      (click)="scroll(contact,'contact')" (scroll)="scrollHandler($event)">
        <a class="nav-link">CONTACT</a>
      </li>
    </ul>
  </links>
</mdb-navbar>
</section>

<div class="text-center">
  <div #about>
    <app-about></app-about>
  </div>
  <div #features>
    <app-features></app-features>
  </div>
  <div #management>
    <app-management></app-management>
  </div>
  <div #contact>
    <app-contact></app-contact>
  </div>
</div>

头文件.component.ts

  scroll(el,name) {
this.activeMenu = name;
this.el =el;
el.scrollIntoView({ behavior: 'smooth', block: 'start'  });

}

上面的这个函数让我在点击菜单项时滚动到正确的 div。

问题是:1)当我滚动到同一页面上的不同组件时,我无法将菜单更改为活动状态。2) URL 不变。

提前致谢。

标签: angulartypescriptroutingangular6

解决方案


基本上您需要在组件位置到达特定位置时触发或调用该方法。

import { Directive, HostListener, Input , ElementRef} from '@angular/core';

@Directive({
  selector: '[appTrackScroll]'
})
export class TrackScrollDirective {


  @Input("appTrackScroll")
  private scrollName; 

   state = 'hide'

  constructor(public el: ElementRef) { }

  @HostListener('window:scroll', ['$event'])
    checkScroll() {
      const componentPosition = this.el.nativeElement.offsetTop
      const scrollPosition = window.pageYOffset
       // You can set the position as per your rquirement.
      if (scrollPosition >= componentPosition) {
        // Enable the menu
      } else {
        // Disable the menu
      }

    }
}

示例演示在这里https://stackblitz.com/edit/angular-zej55w


推荐阅读