滚动经过片段时,Angular 10 获取路由器活动片段?

我试图在导航中突出显示您正在滚动过去的活动片段。


将片段和导航添加到片段很简单并且效果很好,例如:


      class="nav-button unselectable"

      matRipple

      routerLink="/"

      fragment="features"

      [ngClass]="{ 'nav-active': (active_fragment | async) === 'features' }"

但是路由器显然不知道你在滚动哪个元素,所以我试图监听滚动事件并使用 Y 位置检查最近的元素。


但是我的着陆页不是我的导航的孩子,所以 viewchild 不起作用,例如:


导航组件:


  @ViewChild('features', { static: false })

  private _features: ElementRef;


  @HostListener('window:scroll', ['$event'])

  private _update_active_fragment(event: any) {

    event.preventDefault();


    console.log(window.pageYOffset);

    console.log(this._features.nativeElement);

  }

着陆页组件:


  <app-features #features id="features"></app-features>

但是 features native 元素是未定义的。

我的问题是:

  • 我还能如何实现此功能?

  • 如何从导航组件中获取元素 ref?

  • 如何获取导航组件中 features 元素的 y 位置?


人到中年有点甜
浏览 84回答 1
1回答

叮当猫咪

做了一个新的导航服务:public active_fragment: BehaviorSubject<string> = new BehaviorSubject('');&nbsp; constructor(private readonly route: ActivatedRoute) {&nbsp; &nbsp; this.route.fragment.subscribe((frag) => {&nbsp; &nbsp; &nbsp; this.active_fragment.next(frag);&nbsp; &nbsp; });&nbsp; }在我的导航组件中:&nbsp; &nbsp; &nbsp; [ngClass]="{&nbsp; &nbsp; &nbsp; &nbsp; 'nav-active': (navigationService.active_fragment | async) === 'home'&nbsp; &nbsp; &nbsp; }"在包含我的片段的登陆组件中:&nbsp; @ViewChild('features', { read: ElementRef })&nbsp; private _features: ElementRef;&nbsp; @ViewChild('benefits', { read: ElementRef })&nbsp; private _benefits: ElementRef;&nbsp; @HostListener('window:scroll', ['$event'])&nbsp; private _update_active_fragment(event: any) {&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; switch (true) {&nbsp; &nbsp; &nbsp; case window.pageYOffset >=&nbsp; &nbsp; &nbsp; &nbsp; this._some_previous_element.nativeElement.offsetTop &&&nbsp; &nbsp; &nbsp; &nbsp; window.pageYOffset <= this._features.nativeElement.offsetTop: {&nbsp; &nbsp; &nbsp; &nbsp; this.navigationService.active_fragment.next('network-rail-feedback');&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; case window.pageYOffset >= this._features.nativeElement.offsetTop &&&nbsp; &nbsp; &nbsp; &nbsp; window.pageYOffset <= this._benefits.nativeElement.offsetTop: {&nbsp; &nbsp; &nbsp; &nbsp; this.navigationService.active_fragment.next('features');&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript