ScrollToView по горизонтали в Angular - PullRequest
0 голосов
/ 08 апреля 2020

У меня есть горизонтальный ряд элементов с возможностью прокрутки. При выборе элемента с помощью другой кнопки, я хотел бы прокрутить и показать текущий выбранный элемент. ScrollToView в настоящее время не работает для меня.

component. html

 <div>
  <h1>Hi {{ name }}</h1>
  <div class="container">
    <div
    [class.active]="selected === item"
    (click)="select(item)"
    *ngFor="let item of items" class="item">
      {{ 'item-' + item }}
    </div>
  </div>
  <button (click)="select(1)">select 1</button>
  <button (click)="select(5)">select 5</button>
  <button (click)="select(8)">select 8</button>
</div>

component.ts

export class App {
  name: string;
  items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  selected: number;

  select(item){
    this.selected = item
    const el = document.querySelector('.active')
    if(el) el.scrollIntoView()
  }

}

component. css

.container {
  width: 200px;
  height: 50px;
  border: 1px solid black;
  overflow: auto;
  overflow-y: hidden;
  white-space: nowrap;
  display: flex;
  flex: 1;
}

.item {
  width: 30px;
  padding: 10px;
}

.active {
  font-weight: bold;
}

plunkr: https://plnkr.co/edit/lTlJKin4WmwBlJrD

1 Ответ

1 голос
/ 08 апреля 2020

Используйте ViewChildren, например:

@ViewChildren("element", { read: ElementRef }) elements: QueryList<ElementRef>;

поместите переменную ссылки на шаблон "#element"

<div
  #element
  *ngFor="let item of items"
  (click)="select(item)"
  [class.active]="selected === item"
  class="item"
 >
  {{ 'item-' + item }}
</div>

, теперь итерируйте элементы, чтобы найти элемент и вызвать "scrollIntoView () "

  select(selected: number): void {
    this.selected = selected;
    this.elements.forEach((element, i) => {
      if (selected === i) {
        element.nativeElement.scrollIntoView({
          behavior: "smooth",
          block: "nearest",
          inline: "end"
        });
      }
    });
  }

Я создал пример для stackblitz

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...