mr_blond
mr_blond

Reputation: 1730

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

There is an component with items shown with *ngFor. My goal is scrolling down to element with anchor #3.

The code:

@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();
    }
}

There is an jsfiddle example.

I can't figure out how do I set unchors for it?

Upvotes: 3

Views: 1003

Answers (2)

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

You can define some template variable on li elements.

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

And retrieve these elements within your component as follows

@ViewChildren('elements') listItems: QueryList<any>;

And finally change your scroll method to this

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

Upvotes: 1

Shashank Vivek
Shashank Vivek

Reputation: 17504

Try

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

and in component:

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

Here is a sample fiddle.

Upvotes: 2

Related Questions