如果您需要以编程方式触发 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>。
之后,您可以在视图准备好后循环遍历项目并触发对原生 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();
});
}
}
工作堆栈闪电战:https://stackblitz.com/edit/angular-1eha8j
(查看控制台查看是否点击了第 10 项)
注意:在上面的示例中,我使用 forEach 来循环项目,但您可以使用 .find 或简单地获取特定索引处的项目来获取所需的项目。上面的例子只是为了说明通过选择器可以进行很多操作。