Недопустимая ошибка селектора при попытке ссылки на раздел на текущей странице - PullRequest
0 голосов
/ 24 июня 2018

Я делаю страницу с часто задаваемыми вопросами, в которой все вопросы находятся в верхней части в виде гиперссылок.Когда вы нажимаете гиперссылку, вы попадаете на ту часть страницы, где можно прочитать ответ на вопрос.Для этого я пытаюсь использовать решение, представленное здесь Angular2 Маршрутизация с хэштегом на привязку страницы , предоставленную Калояном.Решение ломается для меня в кодовой строке

  const element = document.querySelector("#" + tree.fragment);

Это дает ошибку ERROR DOMException: Failed to execute 'querySelector' on 'Document': '#1' is not a valid selector..Я могу понять, почему я получаю эту ошибку, потому что он ищет селектор, и ввод он получает #fragment.Тем не менее все в потоке stackoverflow, о котором я упоминал, говорят, что это работает, так что, возможно, я делаю что-то не так.Когда я заменяю querySelector на getElementById (tree.fragment), я больше не получаю ошибок, но страница не переходит на раздел, когда я нажимаю на одну из ссылок.Может кто-нибудь сказать мне, какую часть я делаю неправильно или какую часть я пропустил, реализовав решения из упомянутой темы?Спасибо.

Вот мой код:

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

import { Component, OnInit } from '@angular/core';
import { FaqItem } from './faq-item.model';
import { Router, NavigationEnd } from '@angular/router';

@Component({
  selector: 'app-faq',
  templateUrl: './faq.component.html',
  styleUrls: ['./faq.component.css']
})
export class FaqComponent implements OnInit {

  faqItems: FaqItem[] = EXAMPLE_DATA;



  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);
          // const element = document.getElementById(tree.fragment);
          if (element) { element.scrollIntoView(true); }
        }
      }
    });

  }

  ngOnInit() {
  }

}

const EXAMPLE_DATA: FaqItem[] = [
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},

    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},  {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},
    {id: 1, question: 'How do i use the seedcalendar app?', answer: 'please check the getting started tutorial for this'},

]
export class FaqItem {
    id: number;
    question: string;
    answer: string;
}

Код HTML:

<section id="top">
  <ol>
    <li *ngFor="let item of faqItems; let i=index">
        <a [routerLink]="['.']" fragment={{i}}>{{item.question}}</a>
    </li>
  </ol>
<dl>
  <app-faq-item *ngFor="let item of faqItems; let i=index" 
  [question]="item.question" [answer]="item.answer" [attr.id]="i">
</app-faq-item>
</dl>
</section>

1 Ответ

0 голосов
/ 24 июня 2018

Насколько я понимаю, использование fragment для якорных ссылок (я могу ошибаться) заключается в том, что они используются при навигации между маршрутами, и вы хотите, чтобы пользователь однажды переместился в определенную точку на странице.Вы перешли туда.

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

Если это так, вы могли быпросто используйте @ViewChildren:

добавьте templateRef (#answers):

<app-faq-item #answers *ngFor="let item of faqItems; let i=index" [...] [...]>

и обработчик кликов к вопросу:

<a href="javascript:;" (click)="scrollTo(i)">{{item.question}}</a>

и в своем компоненте используйте ViewChildren, чтобы получитьтекущий элемент:

export class FaqComponent implements OnInit {

  faqItems: FaqItem[] = EXAMPLE_DATA;
  @ViewChildren('answers', { read: ViewContainerRef }) answers;

  scrollTo(index: number) {
    const element = this.answers.toArray()[index].element.nativeElement;
    element.scrollIntoView({
      behavior:"smooth",
      block: "start", 
      inline: "nearest"
    });
  }

Вот Демо .

...