gpt4 book ai didi

angular - 区分ngFor中同名的viewChild

转载 作者:行者123 更新时间:2023-12-04 14:21:04 25 4
gpt4 key购买 nike

在我的 html 组件中,我有一个 *ngFor像这样生成多个元素的循环:

<div *ngFor="let item of items">
<p #itemName>{{item.name}}</p>
</div>

然后在我的 .ts 组件中访问 <p> ,我在做:

@ViewChild('itemName') itemName: ElementRef;

作为我用它做某事的例子:

this.itemName.nativeElement.focus();

我的问题是因为可以有多个 p标签,将有多个实例 itemName在 .ts 文件中,当试图用它做一些事情时,例如上面的例子,第一个实例 itemName会很专注。

如何确定 itemName 的哪个实例?我现在在吗?

最佳答案

您可以使用@viewChildren 来选择具有相同模板引用变量的多个元素。您应该使用 toArray() 方法将 QueryList 转换为数组,以便遍历元素。

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

....

@ViewChildren('itemName') itemName: QueryList<ElementRef>;

ngAfterViewInit() {
this.itemName.toArray().forEach(el => {
el.nativeElement.focus();
});
}

关于angular - 区分ngFor中同名的viewChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54880623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com