如何在 Angular 2 中为 *ngFor 元素设置锚点?

How do I set anchors for *ngFor elements in Angular2+?

有一个组件的项目显示为 *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

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

尝试

    <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.

您可以在 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<any>;

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

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