首页 > 解决方案 > 如何在 *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'”。有什么解决办法吗?

标签: angularionic-framework

解决方案


不要在模板中处理这个逻辑(非常脆弱),而是尝试使用@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


推荐阅读