0

I'm trying to create a dynamic number of text inputs and bind each to a value in an array of strings in object a. This seems to generate weird issues. Every letter I type into a textbox unselects the textbox, and unpredictable things happen when I add new items to the list. Any ideas what is going on?

Template:

<div *ngFor="let listItem of a.list; let i = index;">
    <input type="text" name="sourceText" id="sourceText" class="form-control"
        placeholder="Enter item" required [(ngModel)]="a.list[i]">
</div>
<a (click)="a.list.push('')">Add new item...</a>

Typescript:

export class MyClass {
    a: { list: string[] };

    constructor() {
        this.reset();
    }

    reset() {
        this.a = {list: ['']};
    }
}
seanjib
  • 1
  • 1

2 Answers2

0

It is because you have given same id for all the elements id="sourceText". Try appending the index to the id id="source text"+i and then see, it should work. Id should be unique for all the elements.

monica
  • 1,454
  • 14
  • 28
0

Try this -

<div *ngFor="let listItem of a.list; let i = index;">
    <input type="text" name="sourceText"+i id="sourceText"+i class="form-control"
    placeholder="Enter item" required [(ngModel)]="a.list[i]">
</div>

The problem is the fact that it contains same name(optional) and ids(should've been unique for every resource tag).

Therefore, change your id tag "sourceText"+i and name tag like above and see if it works.

tom
  • 3,720
  • 5
  • 26
  • 48