You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 2中如何将ngFor循环内的item.id赋值给引用变量?

How to Assign item.id to a Variable in Angular 2+ Template

Hey there! Let's break down why your original approach isn't working and how to fix it properly.

First, let's clarify the core issue: Angular's template reference variables (like #myVar) are designed to reference elements, components, or directives — you can't directly assign a raw value like item.id to them the way you might expect. Plus, combining *ngFor with *ngIf creates conditional rendering scope issues that prevent you from capturing the value reliably.

Here are two tailored solutions based on what you're trying to achieve:

1. Capture item.id in a Component Class Variable

If you need to use the matched ID in your component's TypeScript logic, this is the most straightforward approach:

Step 1: Define a variable in your component

// your-component.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html'
})
export class YourComponent {
  users = [...]; // Your user dataset
  update = { business_type: '...' }; // Your existing update object
  matchedUserId: number | undefined; // Variable to store the target ID
}

Step 2: Assign the value in the template

Use Angular's *ngIf assignment syntax (available in Angular 4+) to capture the matching item, then pass its ID to your component variable:

<!-- your-component.component.html -->
<ng-container *ngFor="let item of users">
  <!-- Capture the matching item with *ngIf's let syntax -->
  <ng-container *ngIf="item.method == update.business_type; let matchedItem">
    <td>{{ matchedItem.id }}</td>
    <!-- Assign the ID to your component variable (hidden container avoids extra DOM elements) -->
    <ng-container *ngIf="(matchedUserId = matchedItem.id)"></ng-container>
  </ng-container>
</ng-container>

If you prefer more explicit control, use a helper method in your component:

// Add this to your component class
assignUserId(id: number): boolean {
  this.matchedUserId = id;
  return false; // Return false so the container doesn't render
}
<!-- Update the template to use the helper -->
<ng-container *ngFor="let item of users">
  <td *ngIf="item.method == update.business_type; let matchedItem">
    {{ matchedItem.id }}
    <ng-container *ngIf="assignUserId(matchedItem.id)"></ng-container>
  </td>
</ng-container>

2. Use Template Reference Variables for Template-Only Access

If you only need to reference the ID within the template (e.g., for styling or inline logic), attach a template variable to the <td> element:

<ng-container *ngFor="let item of users">
  <td #matchedTd *ngIf="item.method == update.business_type">
    {{ item.id }}
  </td>
</ng-container>

<!-- Example: Use the value later in the template -->
<div *ngIf="matchedTd">Matched User ID: {{ matchedTd.textContent.trim() }}</div>

Note: If multiple items match the condition, matchedTd will reference the last rendered <td>. To access all matching elements, use @ViewChildren in your component:

// Add this to your component class
import { ViewChildren, ElementRef, QueryList, AfterViewInit } from '@angular/core';

export class YourComponent implements AfterViewInit {
  @ViewChildren('matchedTd') matchedTds!: QueryList<ElementRef>;

  ngAfterViewInit() {
    // Loop through all matched elements to retrieve IDs
    this.matchedTds.forEach(td => {
      const id = td.nativeElement.textContent.trim();
      console.log('Matched ID:', id);
    });
  }
}

Why Your Original Code Failed

Your initial setup tried to use a template variable to store a raw value, which isn't how Angular's template reference variables work. Additionally, the <ng-container> doesn't create a persistent scope for the variable, so even if you tried to assign it, the value wouldn't be accessible outside the immediate conditional block.

内容的提问来源于stack exchange,提问作者hari prasanth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:27:58