2

Trying to implement a add/remove sub-item entry; increment/decrement buttons add slots into the array and input fields are added/removed automatically:

<div *ngFor="let item of itemsInNewOrder; let i = index">
  <input [(ngModel)]="itemsInNewOrder[i]" xtype="text" name="order" title="order" />
</div>

This is working functionally, but every time a letter is entered into the input, the element is deselected and must be clicked again to enter yet one more letter. How can I solve this?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
dooblr
  • 458
  • 1
  • 5
  • 18

3 Answers3

0

http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

The link above explains change detection in Angular 2. It also describes some other change detection strategies that you might find useful.

Basically since you did a 2 way binding [(ngModel)]="itemsInNewOrder[i]" to the itemsInNewOrder array, Angular is trying to be helpful and update the view for you.

  1. Each keystroke updates your model (itemsInNewOrder)
  2. Angular detects the update
  3. Angular renders the view again with new form controls
  4. Again, these are new form controls so the user hasn't focused one yet. This is why you have to click into the control after every entered character.

You can fix this by removing your 2 way binding and instead listening to the blur event for each input or implementing something described in the link above.

Blur event listening example:

<input (blur)="blurHandler(item,i)" type="text" name="order" title="order" />

Component

blurHandler(val:string,ndx:number) {
  this.itemsInNewOrder[ndx] = val;
}

This might help too

Angular 2 change event - model changes

Community
  • 1
  • 1
bassxzero
  • 4,838
  • 22
  • 34
  • Didn't work, I think because those html commands are still being watched by the changedetector. Yet after detatching, making operations, and reattatching, the data gets removed and the UI updated. Still at a loss. I can't imagine that making nested inputs is a new endeavor but I'm unable to find any mention of this anywhere. – dooblr Nov 01 '16 at 22:04
0

You can also wrap the values into objects. I don't know why you don't lose focus if you do it like this.

Component:

itemsInNewOrder = [{value: 'Soda'}, {value: 'Burger'}, {value: 'Fries'}];

template:

<div *ngFor="let item of itemsInNewOrder; let i = index">
    <input 
      type="text" 
      name="order" 
      title="order" 
      [(ngModel)]="itemsInNewOrder[i].value"/>
  </div>
Kyrsberg
  • 440
  • 4
  • 11
0

The simplest answer to this was that I needed to learn and implement Angular 2's reactive forms library, which is part of Angular 2. Using this, I ran into none of difficulties I was experiencing.

dooblr
  • 458
  • 1
  • 5
  • 18