Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Ngfor , trigger click on nth(x) item

How can i trigger click on specific nth-child(x) item in ngFor listing ?

<ul>
    <li class="list"  *ngFor="let ver of versions; (click)="versionView()">{{ver.name}}</li>
</ul>
like image 845
ShibinRagh Avatar asked Sep 15 '25 05:09

ShibinRagh


1 Answers

If you need to trigger programmatically the click on init (assuming you need a real click event that will also include the propagation, otherwise you can just raise the click event), you can do that using ViewChildren and NgAfterViewInit.

Basically, you can use a selector to acquire all the <li> items:

<ul>
  <li #items class="list" *ngFor="let ver of versions;" (click)="versionView(ver)">{{ver.name}}</li>
</ul>

(note the #items selector).

In your component, you can declare a selector targeting "items": @ViewChildren('items') liItems: QueryList<ElementRef>.

After that, you can loop through the items after the view is ready and trigger the click on the native html element:

  public ngAfterViewInit() {
    const targetItem = 10;
    // If the item is the 10th element, click it.
    this.liItems.forEach((item, index) => {
      if (index === (targetItem - 1)) (item.nativeElement as HTMLElement).click();
    });
  }

Full component code sample:

import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChildren('items') liItems: QueryList<ElementRef>

  public versions: { name: string }[];

  public constructor() {
    this.versions = Array.from({length: 10}).map((_, i) => {
      return { name: i.toString() };
    });
  }

  public versionView(i: {name: string}) {
    console.log('clicked item: ', i);
  }

  public ngAfterViewInit() {
    const targetItem = 10;
    // If the item is the 10th element, click it.
    this.liItems.forEach((item, index) => {
      if (index === (targetItem - 1)) (item.nativeElement as HTMLElement).click();
    });
  }
}

Working stackblitz: https://stackblitz.com/edit/angular-1eha8j

(check the console to see that the item 10 is clicked)

Beware: In the sample above I've used forEach to loop the items, but you can simply acquire the item you need using .find or by simply getting the item at a specific index. The above example is just to show that many manipulations are possible through selectors.

like image 53
briosheje Avatar answered Sep 17 '25 19:09

briosheje