ng-reflect-model shows correct value but not reflecting in input

22,159

Solution 1

Apparently the issue was being caused because Angular wasn't able to track the elements of my array properly. I found this out very hard way. So just adding a trackBy attribute to my ngFor, I was able to resolve this.

Added this to my component:

customTrackBy(index: number, obj: any): any {
  return index;
}

and then in the template:

<div class="margin-bottom-15"
     *ngFor="let assessment of language.assessments; trackBy:customTrackBy">

So basically I am asking angular to track my elements in the array by index. It resolved the issue.

Here assessment is the model for each of the question-answer set.

Solution 2

In case if you are using nested ngFor then name attributes might not unique. It should be unique. So suffix name attribute with indexes of for loop to make it unique.

 <form #f="ngForm" validate>
      <div *ngFor="childItem of parentArray; index as pIndex;">
           <div *ngFor="childArray of childItem.parameters;index as cIndex;">
                 First Name: <input name="childArray-{{pIndex+''+cIndex}}" 
                 type="text" [(ngModel)]="childArray.firstname" required>
                 Last Name: <input name="childArray-{{pIndex+''+cIndex}}" 
                 type="text" [(ngModel)]="childArray.lastname" required>

                <button type="button" [disabled]="!f.valid"
                (click)="submitForm();"> Submit  </button>
            </div>
       </div>
 </form>
Share:
22,159
Pratik Barasia
Author by

Pratik Barasia

Updated on July 09, 2022

Comments

  • Pratik Barasia
    Pratik Barasia almost 2 years

    Encountered a very weird issue where my application misbehaves in a very specific user case. I have a portal where users can add questions and answers and then edit them. In this case when I remove a set(q+a) and then try adding it, the model is getting updated but my view takes values from placeholders and updates itself. Here I am just splicing and pushing values in an array and rendering using ngFor. The last element is a dummy and that is used to enter values which are pushed up.

    Attaching a screenshot if it makes any sense.

    You can see that for the textbox, the ng-reflect-model shows correct question, but the element itself displays the placeholder text.

  • peterh
    peterh about 7 years
    It is probably one of the most useful posts I've read ever here. I think it is the rare case as you don't need to pay more attention to spelling, because your content compensates it. Although you can :-)
  • sige
    sige over 5 years
    \o/ Thanks Peter! You made my day.
  • Mahi
    Mahi over 5 years
    Thanks dude for saving my day