Подтвердить что ты не робот

Angular2 Маршрутизация с помощью Hashtag для привязки страницы

Я хочу добавить некоторые ссылки на мою страницу Angular2, чтобы при щелчке переходите к определенным позициям внутри, например, к тем, что делают обычные хэштеги. Таким образом, ссылки будут чем-то вроде

/users/123#userInfo
/users/123#userPhoto
/users/123#userLikes

и др.

Я не думаю, что мне нужна HashLocationStrategy, поскольку я в порядке с обычным способом Angular2, но если я добавлю напрямую, ссылка фактически перейдет к корню, а не где-нибудь на той же странице. Любое направление оценивается, спасибо.

4b9b3361

Ответ 1

Обновить

Теперь это поддерживается

<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>
this._router.navigate( ['/somepath', id ], {fragment: 'test'});

Добавьте код ниже для вашего компонента, чтобы прокрутить

  import {ActivatedRoute} from '@angular/router'; // <-- do not forget to import

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

оригинал

Это известная проблема, которая отслеживается по адресу https://github.com/angular/angular/issues/6595.

Ответ 2

Хотя ответ Гюнтера верен, он не охватывает "переход к" части тега привязки.

Поэтому дополнительно к:

<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>
this._router.navigate( ['/somepath', id ], {fragment: 'test'});

... в компоненте (родительском), где вам нужно поведение "перейти к", добавьте:

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

class MyAppComponent {
  constructor(router: Router) {

    router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = router.parseUrl(router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(true); }
        }
      }
    });

  }
}

Обратите внимание, что это обходной путь ! Следуйте этой проблеме GitHub для будущих обновлений. Благодарности Виктору Савкину за предоставленное решение!

Ответ 3

Извините, что ответил на него немного поздно; В документации по angular маршрутизации есть предопределенная функция, которая помогает нам в маршрутизации с помощью хэштега для привязки к странице, т.е. anchorScrolling: 'enabled'

Шаг 1: - Сначала импортируйте RouterModule в файл app.module.ts: -

imports:[ 
    BrowserModule, 
    FormsModule,
    RouterModule.forRoot(routes,{
      anchorScrolling: 'enabled'
    })
  ],

Шаг 2: - Перейдите на страницу HTML, создайте навигацию и добавьте два важных атрибута, таких как [routerLink] и фрагмент, для сопоставления с соответствующим Div ID: -

<ul>
    <li> <a [routerLink] = "['/']"  fragment="home"> Home </a></li>
    <li> <a [routerLink] = "['/']"  fragment="about"> About Us </a></li>
  <li> <a [routerLink] = "['/']"  fragment="contact"> Contact Us </a></li>
</ul>

Шаг 3: - Создайте раздел /div, сопоставив имя с фрагментом: -

<section id="home" class="home-section">
      <h2>  HOME SECTION </h2>
</section>

<section id="about" class="about-section">
        <h2>  ABOUT US SECTION </h2>
</section>

<section id="contact" class="contact-section">
        <h2>  CONTACT US SECTION </h2>
</section>

Для справки, я добавил приведенный ниже пример, создав небольшую демонстрацию, которая поможет решить вашу проблему.

Demo : https://routing-hashtag-page-anchors.stackblitz.io/

Ответ 4

Немного поздно, но здесь я нашел ответ, который работает:

<a [routerLink]="['/path']" fragment="test" (click)="onAnchorClick()">Anchor</a>

И в компоненте:

constructor( private route: ActivatedRoute, private router: Router ) {}

  onAnchorClick ( ) {
    this.route.fragment.subscribe ( f => {
      const element = document.querySelector ( "#" + f )
      if ( element ) element.scrollIntoView ( element )
    });
  }

Вышеприведенное не автоматически прокручивает представление, если вы попали на страницу с привязкой, поэтому я использовал вышеупомянутое решение в моем ngInit, чтобы оно могло работать и с этим:

ngOnInit() {
    this.router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = this.router.parseUrl(this.router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(element); }
        }
      }
    });
  }

Обязательно импортируйте Router, ActivatedRoute и NavigationEnd в начале вашего компонента, и все должно быть в порядке.

Источник

Ответ 5

Ни один из предыдущих ответов не работал у меня. В последней попытке я попытался в своем шаблоне:

<a (click)="onClick()">From Here</a>
<div id='foobar'>To Here</div>

С этим в моем .ts:

onClick(){
    let x = document.querySelector("#foobar");
    if (x){
        x.scrollIntoView();
    }
}

И он работает как ожидается для внутренних ссылок. Это фактически не использует теги привязки, чтобы он вообще не касался URL.

Ответ 6

Решения выше не работали для меня... Это сделало это:

Сначала подготовьте MyAppComponent для автоматической прокрутки в ngAfterViewChecked()...

import { Component, OnInit, AfterViewChecked } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component( {
   [...]
} )
export class MyAppComponent implements OnInit, AfterViewChecked {

  private scrollExecuted: boolean = false;

  constructor( private activatedRoute: ActivatedRoute ) {}

  ngAfterViewChecked() {

    if ( !this.scrollExecuted ) {
      let routeFragmentSubscription: Subscription;

      // Automatic scroll
      routeFragmentSubscription =
        this.activatedRoute.fragment
          .subscribe( fragment => {
            if ( fragment ) {
              let element = document.getElementById( fragment );
              if ( element ) {
                element.scrollIntoView();

                this.scrollExecuted = true;

                // Free resources
                setTimeout(
                  () => {
                    console.log( 'routeFragmentSubscription unsubscribe' );
                    routeFragmentSubscription.unsubscribe();
                }, 1000 );

              }
            }
          } );
    }

  }

}

Затем перейдите к my-app-route отправке prodID hashtag

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

@Component( {
   [...]
} )
export class MyOtherComponent {

  constructor( private router: Router ) {}

  gotoHashtag( prodID: string ) {
    this.router.navigate( [ '/my-app-route' ], { fragment: prodID } );
  }

}

Ответ 7

Все остальные ответы будут работать на angular версии & lt; 6.1. Но если у вас последняя версия, вам не придется делать эти уродливые хаки, так как Angular исправил проблему.

здесь ссылка на выпуск

Все, что вам нужно сделать, это установить scrollOffset с параметром второго аргумента метода RouterModule.forRoot.

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled',
      anchorScrolling: 'enabled',
      scrollOffset: [0, 64] // [x, y]
    })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

Ответ 8

Поскольку свойство фрагмента по-прежнему не обеспечивает привязку прокрутки, это обходное решение сделало для меня трюк:

<div [routerLink]="['somepath']" fragment="Test">
  <a href="#Test">Jump to 'Test' anchor </a>
</div>

Ответ 9

Добавив к Kalyoyan ответ, эта подписка привязана к маршрутизатору и будет жить до тех пор, пока страница не будет полностью обновлена. При подписке на события маршрутизатора в компоненте обязательно отмените подписку в ngOnDestroy:

import { OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Subscription } from "rxjs/Rx";

class MyAppComponent implements OnDestroy {

  private subscription: Subscription;

  constructor(router: Router) {
    this.subscription = router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = router.parseUrl(router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(element); }
        }
      }
    });
  }

  public ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Ответ 10

Я только что получил эту работу на моем собственном веб-сайте, поэтому я решил, что стоит разместить мое решение здесь.

<a [routerLink]="baseUrlGoesHere" fragment="nameOfYourAnchorGoesHere">Link Text!</a>

<a name="nameOfYourAnchorGoesHere"></a>
<div>They're trying to anchor to me!</div>

И затем в своем компоненте обязательно включите это:

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

 constructor(private route: ActivatedRoute) { 
     this.route.fragment.subscribe ( f => {
         const element = document.querySelector ( "#" + f )
         if ( element ) element.scrollIntoView ( element )
     });
 }

Ответ 11

После прочтения всех решений я искал компонент, и я нашел тот, который выполняет именно то, что задал оригинальный вопрос: прокрутка для привязки ссылок. https://www.npmjs.com/package/ng2-scroll-to

Когда вы устанавливаете его, вы используете синтаксис, например:

// app.awesome.component.ts
@Component({
   ...
   template: `...
        <a scrollTo href="#main-section">Scroll to main section</a>
        <button scrollTo scrollTargetSelector="#test-section">Scroll to test section</a>
        <button scrollTo scrollableElementSelector="#container" scrollYTarget="0">Go top</a>
        <!-- Further content here -->
        <div id="container">
            <section id="main-section">Bla bla bla</section>
            <section id="test-section">Bla bla bla</section>
        <div>
   ...`,
})
export class AwesomeComponent {
}

Это сработало очень хорошо для меня.

Ответ 12

Используйте это для модуля маршрутизатора в app-routing.module.ts:

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    useHash: true,
    scrollPositionRestoration: 'enabled',
    anchorScrolling: 'enabled',
    scrollOffset: [0, 64]
  })],
  exports: [RouterModule]
})

Это будет в вашем HTML:

<a href="#/users/123#userInfo">

Ответ 13

Простое решение, которое работает для страниц без каких-либо параметров запроса, совместимо с браузером/переходом, маршрутизатором и глубокой связью.

<a (click)="jumpToId('anchor1')">Go To Anchor 1</a>


ngOnInit() {

    // If your page is dynamic
    this.yourService.getWhatever()
        .then(
            data => {
            this.componentData = data;
            setTimeout(() => this.jumpToId( window.location.hash.substr(1) ), 100);
        }
    );

    // If your page is static
    // this.jumpToId( window.location.hash.substr(1) )
}

jumpToId( fragment ) {

    // Use the browser to navigate
    window.location.hash = fragment;

    // But also scroll when routing / deep-linking to dynamic page
    // or re-clicking same anchor
    if (fragment) {
        const element = document.querySelector('#' + fragment);
        if (element) element.scrollIntoView();
    }
}

Тайм-аут - это просто позволить странице загружать любые динамические данные, "защищенные" с помощью * ngIf. Это также можно использовать для прокрутки вверху страницы при смене маршрута - просто укажите основной тег привязки по умолчанию.

Ответ 14

Вот еще один способ обхода проблемы с ответом на JavierFuentes:

<a [routerLink]="['self-route', id]" fragment="some-element" (click)="gotoHashtag('some-element')">Jump to Element</a>

в script:

import {ActivatedRoute} from "@angular/router";
import {Subscription} from "rxjs/Subscription";

export class Links {
    private scrollExecuted: boolean = false;

    constructor(private route: ActivatedRoute) {} 

    ngAfterViewChecked() {
            if (!this.scrollExecuted) {
              let routeFragmentSubscription: Subscription;
              routeFragmentSubscription = this.route.fragment.subscribe(fragment => {
                if (fragment) {
                  let element = document.getElementById(fragment);
                  if (element) {
                    element.scrollIntoView();
                    this.scrollExecuted = true;
                    // Free resources
                    setTimeout(
                      () => {
                        console.log('routeFragmentSubscription unsubscribe');
                        routeFragmentSubscription.unsubscribe();
                      }, 0);
                  }
                }
              });
            }
          }

        gotoHashtag(fragment: string) {
            const element = document.querySelector("#" + fragment);
            if (element) element.scrollIntoView(element);
        }
}

Это позволяет пользователю напрямую прокручивать элемент, если пользователь непосредственно приземляется на странице с хэштегом в URL-адресе.

Но в этом случае я подписал маршрут Fragment в ngAfterViewChecked, но ngAfterViewChecked() получает вызовы непрерывно за каждый ngDoCheck, и он не позволяет пользователю прокручивать назад, поэтому routeFragmentSubscription.unsubscribe вызывается после время ожидания 0 миллисекунд после просмотра прокручивается до элемента.

Дополнительно метод gotoHashtag определяется для прокрутки к элементу, когда пользователь специально нажимает на тег привязки.

Update:

Если url имеет querystrings, [routerLink]="['self-route', id]" в якоре не сохранит querystrings. Я пробовал использовать обходной путь для этого же:

<a (click)="gotoHashtag('some-element')">Jump to Element</a>

constructor( private route: ActivatedRoute,
              private _router:Router) {
}
...
...

gotoHashtag(fragment: string) {
    let url = '';
    let urlWithSegments = this._router.url.split('#');

    if(urlWithSegments.length){
      url = urlWithSegments[0];
    }

    window.location.hash = fragment;
    const element = document.querySelector("#" + fragment);
    if (element) element.scrollIntoView(element);
}

Ответ 15

Я была такая же проблема. Решение: использование View port Scroller https://angular.io/api/common/ViewportScroller#scrolltoanchor

- код app-routing.module.ts:

import { PageComponent } from './page/page.component';

const routes: Routes = [
   path: 'page', component: PageComponent },
   path: 'page/:id', component: PageComponent }
];

- Компонент HTML

  <a (click) = "scrollTo('typeExec')">
    <mat-icon>lens</mat-icon>
  </a>

- Код компонента:

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


    export class ParametrageComponent {

      constructor(private viewScroller: ViewportScroller) {}

      scrollTo(tag : string)
      {
        this.viewScroller.scrollToAnchor(tag);
      }

    }

Ответ 16

Эта работа для меня! Это ngFor, чтобы он динамически привязывал теги, нужно подождать их рендеринга

HTML:

<div #ngForComments *ngFor="let cm of Comments">
    <a id="Comment_{{cm.id}}" fragment="Comment_{{cm.id}}" (click)="jumpToId()">{{cm.namae}} Reply</a> Blah Blah
</div>

Мой файл TS:

private fragment: string;
@ViewChildren('ngForComments') AnchorComments: QueryList<any>;

ngOnInit() {
      this.route.fragment.subscribe(fragment => { this.fragment = fragment; 
   });
}
ngAfterViewInit() {
    this.AnchorComments.changes.subscribe(t => {
      this.ngForRendred();
    })
}

ngForRendred() {
    this.jumpToId()
}

jumpToId() { 
    let x = document.querySelector("#" + this.fragment);
    console.log(x)
    if (x){
        x.scrollIntoView();
    }
}

Не забудьте импортировать этот ViewChildren, QueryList т.д. И добавить конструктор ActivatedRoute !!

Ответ 17

Я только что протестировал очень полезный плагин, доступный в nmp - ngx-scroll-to, который отлично работает для меня. Однако он разработан для Angular 4+, но, возможно, кто-то найдет этот ответ полезным.

Ответ 18

Я испробовал большинство из этих решений, но столкнулся с проблемами, оставив и вернувшись с другим фрагментом, который не будет работать, поэтому я сделал что-то немного другое, что работает на 100%, и избавился от уродливого хэша в URL.

Это лучший способ, чем я видел до сих пор.

import { Component, OnInit, AfterViewChecked, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

@Component({
    selector: 'app-hero',
    templateUrl: './hero.component.html',
    styleUrls: ['./hero.component.scss']
})
export class HeroComponent implements OnInit, AfterViewChecked, OnDestroy {
    private fragment: string;
    fragSub: Subscription;

    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        this.fragSub = this.route.fragment.subscribe( fragment => { this.fragment = fragment; })
    }

    ngAfterViewChecked(): void {
        try {
            document.querySelector('#' + this.fragment).scrollIntoView({behavior: 'smooth'});
            window.location.hash = "";
          } catch (e) { }
    }

    ngOnDestroy() {
        this.fragSub.unsubscribe();
    }
}

Ответ 19

В отличие от других ответов, я также добавил бы focus() вместе с scrollIntoView(). Также я использую setTimeout так как он переходит на верх в противном случае при изменении URL. Не уверен, что было причиной этого, но, кажется, setTimeout делает обходной путь.

Происхождение:

<a [routerLink] fragment="some-id" (click)="scrollIntoView('some-id')">Jump</a>

Место назначения:

<a id="some-id" tabindex="-1"></a>

Машинопись:

scrollIntoView(anchorHash) {
    setTimeout(() => {
        const anchor = document.getElementById(anchorHash);
        if (anchor) {
            anchor.focus();
            anchor.scrollIntoView();
        }
    });
}

Ответ 20

если добавление этих идентификаторов элементов к URL-адресу не имеет значения, следует рассмотреть эту ссылку:

Angular 2 - привязка ссылок к элементу на текущей странице

// html
// add (click) event on element
<a (click)="scroll({{any-element-id}})">Scroll</a>

// in ts file, do this
scroll(sectionId) {
let element = document.getElementById(sectionId);

  if(element) {
    element.scrollIntoView(); // scroll to a particular element
  }
 }

Ответ 21

В HTML файл:

<a [fragment]="test1" [routerLink]="['./']">Go to Test 1 section</a>

<section id="test1">...</section>
<section id="test2">...</section>

В файле TS:

export class PageComponent implements AfterViewInit, OnDestroy {

  private destroy$$ = new Subject();
  private fragment$$ = new BehaviorSubject<string | null>(null);
  private fragment$ = this.fragment$$.asObservable();

  constructor(private route: ActivatedRoute) {
    this.route.fragment.pipe(takeUntil(this.destroy$$)).subscribe(fragment => {
      this.fragment$$.next(fragment);
    });
  }

  public ngAfterViewInit(): void {
    this.fragment$.pipe(takeUntil(this.destroy$$)).subscribe(fragment => {
      if (!!fragment) {
        document.querySelector('#' + fragment).scrollIntoView();
      }
    });
  }

  public ngOnDestroy(): void {
    this.destroy$$.next();
    this.destroy$$.complete();
  }
}