Как использовать bootstrap scrollspy в проекте angular 7?

У меня есть преобразование базовой html-страницы с компонентом bootstrap scrollspy, и моя навигация не работает (без изменений при прокрутке страницы).

Я установил bootstrap 4 с помощью следующей команды:

npm install bootstrap

Нет никаких изменений при прокрутке страницы или когда я нажимаю на меню, нет «активного» флага.

Вы можете помочь мне ? Спасибо :)


person Jérémy    schedule 14.02.2019    source источник
comment
проверьте это здесь: stackoverflow.com/questions/52154787/   -  person nircraft    schedule 15.02.2019


Ответы (1)


проверьте решение здесь, используя directive вместо spyScroll. Он прослушивает событие прокрутки на странице и выделяет текущий раздел в поле зрения.

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

@Directive({
    selector: '[scrollSpy]'
})
export class ScrollSpyDirective {
    @Input() public spiedTags = [];
    @Output() public sectionChange = new EventEmitter<string>();
    private currentSection: string;

    constructor(private _el: ElementRef) {}

    @HostListener('scroll', ['$event'])
    onScroll(event: any) {
        let currentSection: string;
        const children = this._el.nativeElement.children;
        const scrollTop = event.target.scrollTop;
        const parentOffset = event.target.offsetTop;
        for (let i = 0; i < children.length; i++) {
            const element = children[i];
            if (this.spiedTags.some(spiedTag => spiedTag === element.tagName)) {
                if ((element.offsetTop - parentOffset) <= scrollTop) {
                    currentSection = element.id;
                }
            }
        }
        if (currentSection !== this.currentSection) {
            this.currentSection = currentSection;
            this.sectionChange.emit(this.currentSection);
        }
    }

}

В AppComponent:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  currentSection = 'section1';

  onSectionChange(sectionId: string) {
    this.currentSection = sectionId;
  }

  scrollTo(section) {
    document.querySelector('#' + section)
    .scrollIntoView();
  }
}

AppComponent.html:

 <h1>Current Section : [{{currentSection}}]</h1>


<h2>Menu</h2>
<div (click)="scrollTo('section1')" [ngClass]="{ 'current-section': currentSection === 'section1' }">Section 1 
</div>
<div (click)="scrollTo('section2')" [ngClass]="{ 'current-section': currentSection === 'section2' }">Section 2 
</div>
<div (click)="scrollTo('section3')" [ngClass]="{ 'current-section': currentSection === 'section3' }">Section 3
</div>
<div (click)="scrollTo('section4')" [ngClass]="{ 'current-section': currentSection === 'section4' }">Section 4 
</div>
<br/>


<div id="parentDiv" scrollSpy [spiedTags]="['DIV']" (sectionChange)="onSectionChange($event)" style="height:150px;overflow-y: scroll;">
  <div id="section1">
    <h2 style="margin:0">Section 1</h2>
    <lorem-ipsum></lorem-ipsum>
  </div>
  <div id="section2">
    <h1>Section 2</h1>
    <lorem-ipsum></lorem-ipsum>
  </div>
  <div id="section3">
    <h1>Section 3</h1>
    <lorem-ipsum></lorem-ipsum>
  </div>
  <div id="section4">
    <h1>Section 4</h1>
    <lorem-ipsum></lorem-ipsum>
  </div>
</div>
<br/>

В app.component.css:

.current-section {
  background-color: cornflowerblue
}
.current-section::after { 
  content: "\039e";
  background-color: yellow; 
  color: red;

}
person nircraft    schedule 15.02.2019
comment
@nircraft, как сделать высоту родительского div динамической в ​​зависимости от высоты области просмотра, а не фиксированной?? (150 пикселей в вашем примере или любое фиксированное значение) - person EddyG; 14.06.2019
comment
Привет .. можно ли добавить плавную прокрутку по щелчку div - person Eswar; 14.05.2020
comment
.scrollIntoView({блок: 'конец', поведение: 'гладкое' }); после добавления этой прокрутки происходит плавно. - person Eswar; 14.05.2020
comment
Кто-нибудь знает, как я могу адаптировать это для работы с вложенными div? - person d0rf47; 26.08.2020
comment
@Eswar '.scrollIntoView({блок: 'начало', поведение: 'плавно' });'* конец должен быть началом - person Godstime Osarobo; 12.05.2021