【问题标题】:How do I set anchors for *ngFor elements in Angular2+?如何在 Angular 2 中为 *ngFor 元素设置锚点?
【发布时间】:2020-01-01 19:36:23
【问题描述】:

有一个带有 *ngFor 显示项目的组件。我的目标是向下滚动到带有锚 #3 的元素。

代码:

@Component({
  selector: 'my-app',
  template: `
    <button (click)="scroll(3)">scroll 2</button>
    <li *ngFor="let item of itemList; let i = index" [attr.data-index]="i">{{i}} {{item}}</li>
  `,
})
class HomeComponent {
    text = 'foo';
    testObject = {fieldFirst:'foo'};
    itemList = [
       //...
    ];

    scroll(el: HTMLElement) {
        el.scrollIntoView();
    }
}

有一个 jsfiddle example

我不知道如何为其设置取消点?

【问题讨论】:

  • 你试过我建议的答案了吗?

标签: javascript html angular scroll ngfor


【解决方案1】:

试试

    <button (click)="scroll('3')">scroll to 3</button>
    <li *ngFor="let item of itemList; let i = index" [attr.data-index]="i" [attr.id]="i">{{i}} -->  {{item}}</li>
    <div #target>target</div>

组件中:

    scroll(id: string) {
      const el = document.getElementById(id)
        el.scrollIntoView();
   }

Here is a sample fiddle.

【讨论】:

  • @Brandon :小提琴似乎工作正常。你能不能更好地解释一下。它适用于id="0"
  • @Brandon : :D 哈哈
【解决方案2】:

您可以在li 元素上定义一些模板变量。

<button (click)="scroll(3)">scroll 2</button>
<li *ngFor="let item of itemList; let i = index" #elements>{{i}} {{item}}</li>
<div #target>target</div>

并在您的组件中检索这些元素,如下所示

@ViewChildren('elements') listItems: QueryList&lt;any&gt;;

最后将您的 scroll 方法更改为此

scroll(id) {
    const el = this.listItems.toArray()[id].nativeElement;
    el.scrollIntoView();
}

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 2017-01-13
    • 2018-11-29
    • 2017-12-05
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多