0

I am trying to increment a value of my program using an input number. For reasons, I need my value to always be equal to the one in the Input. My action is basically just doing value = inputValue.

I managed to get my Input value using @ViewChild, but everytime I change its value, it lose focus and I need to click on it again. I have no clue why it is happening and how to fix it, hope you can help me guys ! (Refactoring isn't a problem)

Following is a very simplified version of my code.

<div *ngFor="let x of (myArray | async)">
 <input (input)="myFunction()" [value]="x.value" #myInput type="number">
</div>
@ViewChield('myInput') myInput: ElementRef
myArray: Observable<Array<Object>>;

myFunction() {
 this.store.dispatch(new Action(this.myInput.nativeElement.value));
}
Mambo
  • 197
  • 1
  • 10
  • 1
    just add a `this.myInput.nativeElement.focus()` after dispatching, so that the element will be focused again. – briosheje Jun 06 '19 at 10:26
  • Nope, doesn't change anything sadly... – Mambo Jun 06 '19 at 10:31
  • it is happened, because you are changing `x.value` and you are using `x` in a `ngFor`. So when `x` is changed by input, angular runs change detection, and reloads list – porgo Jun 06 '19 at 10:32

1 Answers1

0

Problem is probably that ngFor will draw list elements again unless there you set trackBy function. Since your div has been redrawn, input will be too and that means you will lose focus because element has been changed.

https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5

Also it would perhaps be a good idea to add a debounce time, in order not to dispatch actions unless user stopped typing.

When @ViewChild is used in *ngFor it will access first list item. @ViewChildren can be used for accessing all items.

angular viewChild for dynamic elements inside ngFor

RandomCode
  • 403
  • 4
  • 9