0
votes

I am trying to iterate over form controls and try to display fields. The fields are getting shown without any issue and also on save properly binding values and displaying output. The problem I am facing is, on key press on those fields, cursor is getting out of focus and not able to enter more than 1 character.

I've simplified the project and created below demo. Added 2 fields, 1 is working with normal loop another is not working on control looping. Not sure what is going wrong.

https://stackblitz.com/edit/angular-ivy-ndnzjd

1
Why are you using control looping, what is the purpose?Chellappan வ
@Chellappanவ, I want to display the form controls iterating the group.controls. The demo is just displaying a static field so please don't get confused. I wanted to simplify the example. Do you know from the stackblitz demo why I can't input more than 1 character at a time and the focus is getting out?Koushik Roy

1 Answers

1
votes

Every time valuechanges on input field, toArray() method gets called and all elements inside ngFor gets rerendered again, that's why focus on input getting out.

You can solve this issue by using trackBy function on ngFor. The trackBy function takes the index and the current item as arguments and needs to return the unique identifier for this item.

component.html

<div *ngFor="let item of toArray(form.controls);trackBy:trackByIndex" class="form-row">not working
          <input [formControlName]="mytestfield" [id]="mytestfield" />
 </div>

component.ts

 trackByIndex(index,value){
    return index;
  }

Example