0

I'm trying to develop an angular application. I am dynamically generates input html element using ngFor from an array and I am giving the ID for the element as inputElem_{{index}}. If I'm trying to delete second last element and add new element I am getting two element with same name and value given in the both input box are getting emptied and showing as invalid in 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);
}
4
  • As you want to create dynamic input form input you can create it using the Reactive Form that is by using FormGroup and FormArray by using it you wont get any errors Commented May 14, 2019 at 6:35
  • Can you provide a Stackblitz example and explain what you want to achieve more specifically? Are you trying to get the HTML element id to be equal to the object index or the other way around? Commented May 14, 2019 at 6:44
  • @ravi Changing to Reactive Form will take up huge time because the application is large and I am using this approach in each and every corner. Please help me with solution without changing this approach Commented May 14, 2019 at 7:23
  • @Jojofoulk stackblitz.com/edit/… Commented May 14, 2019 at 10:49

1 Answer 1

0

HTML Element name and id should be unique. Here name and index is not unique because while doing any alteration in array(inserting & deleting item) will create element with non-unique id/name

<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>

Try to create unique id by using Math.random()

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

Solution reference

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.