sandrooco
sandrooco

Reputation: 8716

Angular2 Event: keyup exits input

I have an input element bound to a property of my component which should update as of when I change the text in the input field.

My code so far:

<input type="text" #updatetext [value]="item.name" (keyup)="updateItem(item.$key, updatetext.value)" />

The problem is that when I make a keystroke, the element looses focus, means I have to click on it again to continue typing.

How can I solve this? Am I going with the wrong approach?

UPDATE

updateItem simply modifies the array. (I'm using it with firebase/angularfire2 btw.)

updateItem(key: string, newText: string) {
    this.items.update(key, { name: newText });
}

So the data itself is: items: FirebaseListObservable<any[]>; and consists of only the key and name properties (both are strings).

Update 2 It's not because the whole dom element is recreated, or at least shouldn't according to the docs (see "change propagation").

Upvotes: 1

Views: 916

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657078

I assume you are creating the input with *ngFor.

If updateItem() modifies the array that *ngFor iterates over, then the element might be recreated, which is why your element loses focus (it's now a different element).

Simple version (depending on what's going on exactly with your data, this might not work)

items.subscribe(response => {
  for(item in response) {
    var found = this.itemsCopy.find((copy) => copy.name == item.name); 
    if(found.length) {
      found[0].value = item.value
    }
  }
})

Then use itemsCopy in *ngFor.

Upvotes: 1

Related Questions