如何在使用动态名称生成时避免使用具有相同ID /名称的不同html元素

时间:2019-05-14 05:04:31

标签: html angular

我正在尝试开发一个有角度的应用程序。我使用ngFor从数组中动态生成输入html元素,并为该元素提供了ID作为inputElem _ {{index}}。如果我要删除倒数第二个元素并添加新元素,则会得到两个在两个输入框中都具有相同名称和值的元素被清空并在ui中显示为无效

<i class="fa fa-add" (click)="addElem()"></i>
<div class="row" *ngFor="let elemName of elemList; let index=index;">
  <div class="col-md-8">
     <input id="inputElem_{{index}}" name="inputElem_{{index}}" required
        [(ngModel)]="elemName.name"/>
  </div>
  <div class="col-md-2">
     <i class="fa fa-delete" (click)="deleteElem(index)"></i>
  </div>
</div>
deleteElem(index: number) {
   this.elemList.splice(index, 1);
}
addElem() {
   const elem = new Elem();
   this.elemList.push(elem);
}

1 个答案:

答案 0 :(得分:0)

HTML元素的名称和ID应该唯一。这里的名称和索引不是唯一的,因为在数组中进行任何更改(插入和删除项目)会创建具有唯一ID /名称的元素

<div class="row" *ngFor="let elemName of elemList; let index=index;">
  <div class="col-md-8">
     <input id="inputElem_{{elemName.id}}" name="inputElem_{{elemName.id}}" required
        [(ngModel)]="elemName.name"/>
  </div>
  <div class="col-md-2">
     <i class="fa fa-delete" (click)="deleteElem(index)"></i>
  </div>
</div>

尝试使用 Math.random()

创建唯一的ID
export class Elem {
   name: string;
   id: string;
   constructor() {
      this.id = Math.random().toString(36).subStr(2, 9);
   }
}

Solution reference