angular - 如何在 *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
.
将模板中数组的所有元素保存到QueryList
您的 TS 类中,并在所需索引处找到元素 -
您的模板 -
<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
推荐阅读
- types - 如何在 Pascal 中使数据类型“真实”更短
- python - 如何使用 Python 请求发送嵌套元组?
- c# - c# - 在字符串内的数组中插入预定义值
- excel - 如何添加第三个范围以进行协调?
- javascript - 如何重用我的代码在点击时打开 Accordions
- python-3.x - 带日志记录的密码生成器
- pandas - 将行添加到 DataFrame,但与某些列的预先存在的行具有相同的值
- cmake - CMake:用于复制与模式匹配的文件并保留目录结构的自定义命令
- mysql - 从 date_of_birth 获取年龄大于 35 的年龄
- java - java项目中集成测试的最佳文件夹约定