What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snippet:

Inputs that should be changed on click

Currently, all the inputs behave the same way - when clicked, the corresponding model value should change. However, creating individual functions for each input doesn't seem like the most efficient solution.

In scenarios where multiple properties follow the same pattern but correspond to different values in the database, how can I create a generic function to update them in Angular?

<div class="col-sm-8">
            <div class="btn-group">
                <input type="button" name="C0R" (click)="changeSpineBoxValue($event)" [(ngModel)]="examData.ExamCervical.C0R" >
                <input type="button" name="C0C" [(ngModel)]="examData.ExamCervical.C0C">
                <input type="button" name="C0L" [(ngModel)]="examData.ExamCervical.C0L">
            </div>
        </div>

For instance, I have around 100 similar inputs, like:

<input type="button" name="C0L" [(ngModel)]="examData.ExamCervical.C0L">

I want to create a TypeScript function that triggers when any of these inputs are clicked. The function should dynamically change the ngModel value based on the input clicked. Instead of writing individual functions for each input, is there a way to achieve this generically? For example:

changeInputModelValue(inputname: string, value: number){
     //logic to adjust ngmodel based on inputname and value
}

Answer №1

If you want to achieve a similar result, you could consider implementing the following approaches:

<input type="button" name="C0R" (click)="updateInputModel('COR', $event)"/>
updateInputModel(inputName: string, value: number){
     this.examDetails.CervicalExam[inputName] = value;
}

Here's an alternative method:

<input type="button" name="C0R" (click)="updateInputModel($event)"/>
updateInputModel(event: MouseEvent){
     const inputName = event.target.attributes.name.value;
     const value = event.target.attributes.value.value;
     this.examDetails.CervicalExam[inputName] = value;
}

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

How can we efficiently link data to custom objects (models) within a different class while fetching data from the server using the http.get() method in Angular CLI?

Currently in the process of developing an Angular-Cli application that involves multiple models with relational data tables. When fetching data from the server, I need to map this data to corresponding model objects. I've experimented with creating a ...

One effective way to transfer state to a child component using function-based React

My goal is to pass an uploaded file to a child component in React. Both the parent and child components are function-based and utilize TypeScript and Material-UI. In the Parent component: import React from 'react'; import Child from './ ...

Looking for guidance on implementing explicit waits in Protractor for non-angular applications

I have noticed that automating non-angular applications with Protractor can be challenging. Currently, I am using some methods to add an explicit wait to my existing Serenity click and enter functions. However, I am curious if there is a way to automatic ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

What is the solution to the strict mode issue in ANGULAR when it comes to declaring a variable without initializing it?

Hi everyone! I'm currently learning Angular and I've encountered an issue when trying to declare a new object type or a simple string variable. An error keeps appearing. this_is_variable:string; recipe : Recipe; The error messages are as follows ...

Issue with importing MomentJS globally in TypeScript

When it comes to defining global external modules in TypeScript, there is a useful option available. For instance, if you have jQuery library loaded externally, you can set up a global definition without having to include its duplicate in the TypeScript bu ...

Having trouble retrieving information from combineLatest in Angular?

I'm having some trouble with fetching files to include in the post logs. It seems that the data is not being passed down the chain correctly when I attempt to use the pipe function after combining the latest data. This code snippet is part of a data r ...

The meaning behind a textual representation as a specific type of data

This snippet is extracted from the file lib.es2015.symbol.wellknown.d.ts interface Promise<T> { readonly [Symbol.toStringTag]: "Promise"; } The concept of readonly seems clear, and the notation [Symbol.toStringTag] likely refers to "'toStr ...

Using interfaces for typecasting in TypeScript

Consider the code snippet below: let x = { name: 'John', age: 30 } interface Employee { name:string, } let y:Employee = <Employee>x; console.log(y); //y still have the age property, why What is the reason for TypeScript ov ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Can you delve into the origin of the term Modal in the context of Angular and web development?

My understanding of a Modal is that it is a webpage component that opens separately from the main page in order to maintain continuity. Am I correct? I am curious as to why it is referred to as a Modal. Could it be short for modularity? Meaning that vari ...

What is the best way to modify the underline style of a tab in Material UI?

I'm trying to customize the underline of: https://i.stack.imgur.com/J2R1z.png Currently, I am using material ui version 4.12.3 The code snippet for generating my tabs is below: function renderTabs(): JSX.Element { return ( <Tabs className={cla ...

The request to DELETE the employee on the server at http://localhost:3000/employees/$%7Bid%7D could not be processed because it was not found

removeEmployee(id: number): Observable<any> { return this._http.delete('http://localhost:3000/staff/${id}'); } } error:HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'http://localhost:30 ...

Tips for making an ajax call in Angular 6

As a backend developer, I have limited experience with Angular. How can I send an ajax request from Angular to test my API? The request needs to be sent before clearing the localeStorage. Can you provide guidance on how to achieve this? <button (clic ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

Unit testing the error function within the subscribe method in Angular

I've been working on a unit test for the subscribe call, but I'm struggling to cover the error handling aspect of the subscribe method. The handleError function deals with statusCode=403 errors and other status codes. Any assistance would be grea ...

How can we effectively transfer a value from TypeScript/Angular?

I am new to TypeScript and Angular, and I'm struggling with assigning a value to a variable within a function and then using that value outside of the function. In regular JavaScript, I would declare the variable first, define its value in the functio ...

Resolving Circular Dependency Error in Angular Component due to Service Integration Testing

Delving into Angular Unit Testing has been a recent focus of mine as I've begun incorporating mock tests in one of my projects. However, I've hit a roadblock with an error popping up in one of my component tests: Error: NG0200: Circular dependen ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

Having trouble installing sub npm dependencies for a private npm module

I've created an npm private repository using Sinopia and published an app that is a complete end-to-end application built with Angular2 on the UI side. The package.json file contains dependencies such as @angular/core and animations. However, when I ...