0

I have an array of numbers that starts out with nulls [,,,,] and I want to be able to edit any of the numbers in that array. I have the following HTML code.

<ol>
  <li *ngFor="let number of numbers; let in = index;">
    <mat-form-field>
      <!-- <input matInput type="number" (change)="keyupEvent($event, i)" placeholder="number" [value]="numbers[i]"> -->
      <input matInput type="number" name="number-{{in}}" [(ngModel)]="numbers[in]" placeholder="points">
    </mat-form-field>
  </li>
</ol>

when I change a number, the component records the change properly (verified with the following)

<div *ngFor="let number of numbers">
  {{number}}
</div>

The UI starts of looking right, with the following list:

1. (placeholder text)
2. (placeholder text)
3. (placeholder text)
4. (placeholder text)
5. (placeholder text)

But when I enter a 5 into #1, I see the following:

1. 5
2. 5 // Cursor is here.
3. (placeholder text)
4. (placeholder text)
5. (placeholder text)

even though my print (in the divs) shows only the first number being updated.

EDIT: I've confirmed it has something to do with the ngModel bindings (the screen doesn't have the weird behavior when I remove the ngModel)

EDIT2: I had a request for the ts file so here it is:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-number-crunching',
  templateUrl: './number-crunching.component.html',
  styleUrls: ['./number-crunching.component.css']
})
export class NumberCrunchingComponent implements OnInit {

  numbers: Array<number>;

  ngOnInit(){
    this.numbers = new Array(5).fill(null);
  }
}
Matt Westlake
  • 3,499
  • 7
  • 39
  • 80
  • Do you have an indexing offset? `name="number-{{in}}"`. Nothing obvious without seeing your **.ts**, the html part says very little. – Z. Bagley Aug 26 '18 at 02:26
  • @Z.Bagley how would that happen? isn't the index defined in the ngFor? the array is being updated properly, it's just the UI that is funky (input copied and cursor on the next line). – Matt Westlake Aug 26 '18 at 02:29
  • @Z.Bagley see EDIT2 – Matt Westlake Aug 26 '18 at 02:34
  • After a bit of digging, it's because of how `new Array(5).fill(null)` works. If you do `this.numbers = [null, null, null]` it'll update properly. Also, may still need a nested object `this.numbers = [{value: null}, {value: null}, {value: null}]` in case the array of flat values doesn't work alone. – Z. Bagley Aug 26 '18 at 03:21
  • You must implement `trackBy: trackByIndex`, as shown in [this answer](https://stackoverflow.com/q/40314732/1009922). See [this stackblitz](https://stackblitz.com/edit/angular-zmtz3y). – ConnorsFan Aug 26 '18 at 03:28

0 Answers0