首页 > 解决方案 > Angular Textinput 组件不适用于数组

问题描述

我想要一个文本输入组件的集合,其值存储在一个数组中。但是当我使用下面的代码时,值在数组中的位置错误,我找不到错误。

<table>
  <tr *ngFor="let option of this.options;let i = index">
    <td style="width:100%">
      <textinput2 (textchange)="this.options[i] = $event;" class="lessmargin" type="text" [value]="this.options[i]">
      </textinput2>
    </td>
    <td valign="top">
      <button [attr.disabled]="this.options.length >= 3 ? null:''" (click)="this.options.splice(i, 1)" style="top:0;" class="btn btn-outline-danger">-</button>
    </td>
  </tr>
</table>

<a (click)="this.options.push('')" class="showmore">+ weitere Option hinzufügen</a>

Textinput2 组件:

<div class="form-group">
  <label *ngIf="this.placeholder && this.labelsize == 'big'" for={{randomid}}><h5>{{this.placeholder}}</h5></label>
  <label *ngIf="this.placeholder && this.labelsize == 'small'" for={{randomid}}>{{this.placeholder}}</label>
  <input [(ngModel)]="this.value" (change)="this.textchange.emit(this.value)" type={{type}} id={{randomid}} class="form-control" placeholder={{this.placeholder}}>
</div>

谢谢

标签: angulartypescript

解决方案


我真的不明白发生了什么,但你可能需要trackBy在你的 *ngFor中使用

根据文档

定义如何跟踪可迭代项中项目更改的函数。

当在可迭代对象中添加、移动或删除项目时,指令必须重新渲染适当的 DOM 节点。为了最大限度地减少 DOM 中的流失,仅重新渲染已更改的节点。

默认情况下,更改检测器假定对象实例标识了可迭代对象中的节点。当提供此函数时,指令使用调用此函数的结果来标识项目节点,而不是对象本身的标识。

该函数接收两个输入,即迭代索引和节点对象 ID。

您可以在那里了解更多如何使用它


推荐阅读