![](/img/trans.png)
[英]How to set unique template reference variables inside an *ngFor? (Angular)
[英]How can I set a reference variables to a specific item, in *ngFor?
我有这个代码
<ng-container *ngFor="let item of results;let i = index"> <ion-item #triggerElement lines="none">
我需要将引用 #triggerElement 设置为索引为 3 的项目。我该怎么做? 我尝试使用 div
<div *ngIf="i == 2" #triggerElement ></div>
但它给我一个错误:“无法读取未定义的属性'nativeElement'”。 有什么解决办法吗?
不要在模板中处理这个逻辑(非常脆弱),而是尝试使用@ViewChildren
。
将模板中数组的所有元素保存到 TS QueryList
中的 QueryList 中,并在所需索引处找到元素 -
您的模板 -
<ng-container *ngFor="let item of results;let i = index">
<div #triggerElement lines="none">
{{ i }} {{ item }}
</div>
</ng-container>
您的组件 -
import { Component, VERSION, AfterViewInit, ViewChildren, TemplateRef, QueryList, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChildren('triggerElement') elements: QueryList<ElementRef>; <---------
results = [ 'Cheese', 'Tomato', 'Olives', 'Basil'];
ngAfterViewInit() {
const element = this.elements.find((e, index) => index === 3); <-----------
console.log(element);
}
}
我已在此链接重新创建 - https://stackblitz.com/edit/vm-tooltip-directive?file=src%2Fapp%2Fapp.component.ts
看起来它是一个特殊的项目,所以我认为值得将它与 rest 分开。 那么一个简单的解决方案可能是,
<ion-item *ngFor="let item of results | slice:0:2"> .. </ion-item>
<ion-item #triggerElement lines="none"> .. </ion-item>
<ion-item *ngFor="let item of results | slice:3"> .. </ion-item>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.