[Fixed] ngFor on keyValue with a mixture of string and number inputs causes focus to be lost when inputting a number


I have an object with a few values of empty string and other values defaulted to 0.

Once I use *ngFor with the keyValue pipe and use trackBy to keep the dom from refreshing, I will still lose focus when inputting a new number value, but won’t lose focus when inputting text.

Here is the stackblits https://stackblitz.com/edit/angular-ivy-ckzw9g?file=src/app/app.component.html where the issue can be reproduced.


So I am answering it because you asked me, after debugging I figured out that will be beneficial for future reference:

  1. For this code:
<input matInput *ngIf="isNumber(conf.value)" placeholder="Number" name="input{{conf.key}}"
    id="input{{conf.key}}" [(ngModel)]="inputs[conf.key]">

On the very first run this code will create the input text box because you are
passing 0 as number and ngIf will be true so it will create an input box.

  1. When you input any value in the above text box "The inputted value will be a string" by default as no type is mentioned in the textbox, so the above text boxed will be removed and a new text box is created by angular the below one:
 <input matInput *ngIf="isString(conf.value)" placeholder="Text" name="input{{conf.key}}"
    id="input{{conf.key}}" [(ngModel)]="inputs[conf.key]">

This is because when the values of associated object changes, angular runs the change detection to update the view and find out the inputted value is string and creates a new textbox with that value as it is Ngmodeled and object work by reference(it is updating inputs object that is declared in the component) and when you enter the subsequent characters it allows you to keep it focused as long as it satisfy the if condition.

Note: if you add type="number"(that checks isNumber) in the input box, it will allow you to enter as many times you want and it will remained focus.

Leave a Reply

(*) Required, Your email will not be published