如何触发对 ngFor 列表中特定第 nth-child(x) 项的点击?
<ul>
<li class="list" *ngFor="let ver of versions; (click)="versionView()">{{ver.name}}</li>
</ul>
最佳答案
如果您需要以编程方式触发 init 上的点击(假设您需要一个真正的点击事件,该事件也将包含传播,否则您可以只引发点击事件),您可以使用ViewChildren
和 NgAfterViewInit
.
基本上,您可以使用选择器获取所有 <li>
项目:
<ul>
<li #items class="list" *ngFor="let ver of versions;" (click)="versionView(ver)">{{ver.name}}</li>
</ul>
(注意#items 选择器)。
在您的组件中,您可以声明一个针对“项目”的选择器:@ViewChildren('items') liItems: QueryList<ElementRef>
.
之后,您可以在 View 准备好后循环遍历项目并触发对原生 html 元素的点击:
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();
});
}
完整的组件代码示例:
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();
});
}
}
工作堆栈 Blitz :https://stackblitz.com/edit/angular-1eha8j
(检查控制台以查看第 10 项已被单击)
注意:在上面的示例中,我使用 forEach 来循环项目,但您可以使用 .find
简单地获取所需的项目。或者通过简单地获取特定索引处的项目。上面的例子只是为了说明可以通过选择器进行许多操作。
关于javascript - Angular Ngfor,触发点击第 n(x) 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55972027/