Losing focus when number is changed in the input

I need to increment a value in my program based on user input. The value should always match the input number provided by the user. To achieve this, I simply set the value equal to the inputValue.

Although I am able to retrieve the input value using @ViewChild, I'm facing an issue where every time I change the value, it loses focus and requires another click to select it again. I'm not sure why this is happening and how to resolve it, so any help would be appreciated. (I have no problem with refactoring if necessary)

Below is a simplified version of the code snippet:

<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));
}

Answer №1

One potential issue you may encounter is that ngFor will re-render list elements unless a trackBy function is set. This can lead to the input losing focus as the element has been changed during redraw.

Learn more about improving performance with trackBy in Angular 2

Additionally, it might be beneficial to implement a debounce time to prevent dispatching actions while the user is still typing.

Using @ViewChild within *ngFor will only access the first list item, whereas @ViewChildren can help access all items in the list.

Explore using angular viewChild for dynamic elements inside ngFor

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble importing a file in TypeScript?

I needed to utilize a typescript function from another file, but I encountered an issue: I created a file called Module.ts with the following code snippet: export function CustomDirective(): ng.IDirective { var directive: ng.IDirective = <ng.IDire ...

Having difficulty retrieving the user list from Firebase within Angular 6

I am facing an issue with retrieving the list of users from Firebase. Despite having values already set in the database, I am getting empty arrays. The strange thing is that I can successfully add users to the Firebase database and retrieve the list of us ...

Redirect the user to the shop page in Angular 2 if they already have

How can I set up a redirect for the User ID (this.authTokenService.currentUserData.id) if they are the owner of a shop? owner_id: number; private sub: any; ngOnInit() { this.sub = this.httpService.getShops().subscribe(params => { ...

Error detected: An unexpected type incompatibility issue without any obvious incompatibility

Within my code, I am working with an "options" tuple [string, function]. This tuple provides a string that identifies a specific check and a function on which that check is to be performed. It is important to note that the check to be executed must be inst ...

Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into ...

The service remains operational while the button's status undergoes a change

In my data table, each row has a column containing buttons. To ensure that only the button in the clicked row is executed, I include the index of that row in the start/pause timer function. I decided to create these functions in a service so that the time ...

Tips on validating interconnected strings with the help of yup within a react native environment

In my scenario, I am dealing with two date strings called start_date and end_date. Initially, both of these start off as empty strings: export interface FilterSchema { start_date?: any; end_date?: any; } const initialValues: FilterSchema = { s ...

Best Practices for Utilizing NPM Modules with TypeScript

I am interested in developing an npm module using TypeScript. Can anyone suggest a best practice guide on how to start? Here are my questions: Node.js does not natively support TypeScript, so what is the recommended way to publish an npm module? Shoul ...

Tips for effectively utilizing 'ngModel' alongside a form control name

When a user enters or inserts a value into one textarea, I want it to automatically update the other textarea field as well. I thought about using the change function to achieve this, but when I tried to use ng-model with the control name, I encountered a ...

What is the most effective way to retrieve cursors from individual entities in a Google Cloud Datastore query?

I am currently working on integrating Google Cloud Datastore into my NodeJS application. One issue I have encountered is that when making a query, only the end cursor is returned by default, rather than the cursor for each entity in the response. For insta ...

Is there a way to help my KafkaJS consumer stay patient while waiting for a broker to become available?

My KafkaJS consumer setup looks like this: // Create the kafka client const kafka = new Kafka({ clientId, brokers, }); // Create the consumer const consumer = this.kafka.consumer({ groupId, heartbeatInterval: 3000, sessionTimeout: 30000, }); // ...

Issues have been reported with Angular 10's router and anchorScrolling feature when used within a div that is positioned absolutely and has overflow set

I feel like I may be doing something incorrectly, but I can't quite pinpoint the issue. Any help or pointers would be greatly appreciated. My current setup involves Angular 10 and I have activated anchorScrolling in the app-routing.module file. const ...

Using Typescript: Including an additional argument

While experimenting with the code provided in the documentation interface Point { x: number; y: number; } function getX(p: Point) { return p.x; } class CPoint { x: number; y: number; constructor(x: number, y: num ...

Angular requiring me to configure polyfills due to the updates in Webpack 5

While working on my code, I executed ng serve and encountered an error related to polyfills: BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and confi ...

Angular BreakPointObserver is a powerful tool that allows developers

Hey there! I've been working with the BreakpointObserver and have run into an issue while trying to define breakpoints for mobile and tablet devices. It seems that my code is functioning properly for tablets, but not for mobile devices. Upon further i ...

Primeng virtualscroll's offset function works similarly to pagination

Can Primeng Table be used for lazy loading? I am currently using the onLazyLoad function this.apiService.getUsers(this.searchQuery,event.sortField,event.sortOrder===-1? "desc" : "asc",****** PAGE ******).subscribe( res=>{ if(r ...

The 'formGroup' property cannot be bound as it is not recognized as a valid property of 'form' in Angular 7

I tried implementing a login feature using web API with Angular 7, but encountered an error when using <form [formGroup]="loginForm" (submit)="loginFormSubmit()">. What could be causing this issue? https://i.sstatic.net/3M2a5.jpg login.component.ht ...

NgRx Action Payload fails to trigger Effect, but no error messages are generated

I've exhausted all resources on Stack Overflow and still can't seem to figure this out. The issue lies in passing a payload into the 'GetUser' action. My intention is for this payload to go through the effect, and eventually be sent v ...

Cannot retrieve the array stored within my object

Trying to navigate my way through Angular as a newcomer (just transitioning from AngularJS) I'm working with an api call that returns an object containing a subdocument (array). The structure of the object returned by the api is: contact:{ first_ ...

Utilizing formData.append in TypeScript to handle arrays

Hey there! I'm facing an issue while trying to send a form to my Profile endpoint. The problem lies in the 'user:{}' field, as I am unable to properly insert my array data into this specific field. Here is a breakdown of the fields within m ...