[英]Angular Ngfor , trigger click on nth(x) item
如何觸發ngFor列表中特定的nth-child(x)項目的點擊?
<ul>
<li class="list" *ngFor="let ver of versions; (click)="versionView()">{{ver.name}}</li>
</ul>
<ul>
<li class="list" *ngFor="let ver of versions; let i = index" (click)="versionView()">{{ver.name}}</li>
</ul>
您可以添加let i = index
來引用第n個元素,並根據需要使用它。 您可以在versionView()
函數versionView()
其作為參數傳遞,並在那里使用它。
function versionView(i) {
if (i !== NTH_VALUE) {
return
}
// Execute your function here
}
我希望這是您想要的。
你真的很親近 像這樣修改您的代碼:
<ul>
<li class="list" *ngFor="let ver of versions" (click)="versionView(ver)">{{ver.name}}</li>
</ul>
在您相應的組件中,您只需要添加:
versionView(ver: any) {
// Do something with the ver object
}
如果您需要以編程方式觸發init的點擊(假設您需要一個真實的click事件,該事件也將包括傳播 ,否則您可以引發click事件),則可以使用ViewChildren
和NgAfterViewInit
做到這NgAfterViewInit
。
基本上,您可以使用選擇器來獲取所有<li>
項:
<ul>
<li #items class="list" *ngFor="let ver of versions;" (click)="versionView(ver)">{{ver.name}}</li>
</ul>
(請注意#items選擇器)。
在您的組件中,您可以聲明一個針對“ items”的選擇器: @ViewChildren('items') liItems: QueryList<ElementRef>
。
之后,您可以在視圖就緒后循環瀏覽各個項目,並觸發對本機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();
});
}
}
可工作的stackblitz: https ://stackblitz.com/edit/angular-1eha8j
(檢查控制台以查看是否單擊了項目10)
當心:在上面的示例中,我使用過forEach來循環項目,但是您可以使用.find
或通過簡單地在特定索引下獲得項目來簡單地獲取所需的項目。 上面的示例只是為了說明通過選擇器可以進行許多操作。
Click事件每次都會被調用,但是可以通過索引檢查它是否與期望的索引匹配?
<ul> <li class="list" *ngFor="let ver of versions; let i = index" (click)="versionView(i)">{{ver.name}}</li> </ul>
可以在* .ts代碼上檢查索引,如下所示:
function versionView(i) { if (i == NTH_VALUE) { } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.