Pass the parameter name to the controller using the Change function in Angular 2

When creating a string from multiple inputs, I have a requirement to include the name of the input element as the second parameter in a function.

<input [(ngModel)]="programSearched" name="programSearched"(ngModelChange)="stringBuilderOnChangeMaker(programSearched,??programSearched.name??)" </input>

I need to distinguish between different inputs triggering the same onchange action, hence passing the name of the calling input to my method is essential.

stringBuilderOnChangeMaker(value, type) {
    if (type == X) {
    ...
    } else if (type == Y) {
    ...
    }
}

One option is to send a generic value like "program" or 1 as the second parameter, but it would be more elegant and informative to pass the id or name of the element instead.

Answer №1

If you want to access the changed object, you can include the $event parameter in your change method. This will allow you to retrieve the updated object. For example, if your object has a 'name' field, your code would be structured like this:

html

(ngModelChange)="stringBuilderOnChageMaker(programSearched, $event)"

ts

stringBuilderOnChageMaker(value, event) {
    console.log(event); // see what is logged
    const name = event.name;

    if (name == X) {
    ...
    } else if (name == Y) {
    ...
    }
}

Answer №2

It may have been a while, but I recently encountered the same issue and found a solution. Here's how I fixed it:

Here's the HTML code snippet:

(change)="saveChange(product, $event)"

And here's the TypeScript code:

public saveChange(product, event) {

    const name = event.currentTarget.name;
    //..
}

This was tested on Angular version 7.0.6.

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

Node corrupting images during upload

I've been facing an issue with corrupted images when uploading them via Next.js API routes using Formidable. When submitting a form from my React component, I'm utilizing the following functions: const fileUpload = async (file: File) => ...

NGRX effect in Nativescript Angular loses state when the app is suspended on iOS

While using NGRX with Nativescript Angular to manage state and fetch data from the server, I've encountered an issue when suspending the app on IOS. Whenever the app is in the middle of fetching data from the server and gets suspended, the entire proc ...

Error: Unable to locate the specified Typescript function

For the source code, please visit https://github.com/zevrant/screeps I am encountering an issue with my implementation of interfaces in TypeScript. When trying to call the implemented interface, I am getting the following error: "TypeError: spawn.memory.t ...

Error encountered due to a circular reference in the dependency library

Whenever I attempt to run my application, I encounter the following error: > npm start Starting the development server... ts-loader: Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42363b32273121302b323602716c776c71"& ...

Set the enumeration value to a variable

I am facing a problem where it seems impossible to do this, and I need help with finding a solution enum Vehicles { BMW='BMW', TOYOTA='Toyota' } class MyVehicles { public vehicleName: typeof Vehicles =Vehicles; } const veh ...

Encountering an issue while constructing a JSON path in SQL using values from a column

When running the query below, I encountered an error: The second argument of "JSON_VALUE or JSON_QUERY" must be a string literal. SELECT JSON_QUERY(sr.Options, CONCAT('$[', sr.OptionId,']') FROM Survey as sr The 'Options' ...

What is the process for retrieving an element from component interaction?

Is there a way to dynamically change the background color based on component interaction? I am looking for a method to compare the target element with the current element. For example, here is a hypothetical scenario: <span [style.background]=" ...

What is the best way to organize information in a table based on the date

This is my data table https://i.stack.imgur.com/1DNlj.png in the displayed table, the registration dates are sorted with the oldest date at the top. However, I aim to have the newest data displayed first. Below is the code snippet I am using: this.dataSo ...

Utilize Firebase to perform a case-insensitive query

Our Angular/Ionic app requires users to provide their email during registration, which is then saved in the User collection. We also validate if the email is already in use with a query like this: firestore .collection("User") .where("email", "==", ...

Placeholder variable not specified in radio buttons

I am currently facing challenges applying validations to radio buttons in Angular. Normally, I create a #templateRefVariable on the input for other input types, which allows me to access the NgControl and use properties like touched. My goal is to set the ...

Utilizing TypeScript Variables within a Jquery Each Iteration

I have a variable named tableIndexNumber that I need to use in different methods. When trying to access this variable, I use "this.tableIndexNumber" and it works fine. However, I face an issue when using it inside a jQuery each loop because the HTML elemen ...

Enhancing the theme using material-ui@next and typescript

While developing my theme using material-ui, I decided to introduce two new palette options that would offer a wider range of light and dark shades. To achieve this, I extended the Theme type with the necessary modifications: import {Theme} from "material ...

What is the method for activating a button when a user inputs the correct email address or a 10-digit mobile number

How can I enable a button when the user enters a correct email or a 10-digit mobile number? Here is my code: https://stackblitz.com/edit/angular-p5knn6?file=src%2Findex.html <div class="login_div"> <form action=""> <input type="text" ...

Guide on setting up staticfile_buildpack header configuration for an Angular application

After creating a build with ng build --prod, the dist/AppName folder was generated. Inside this folder, I found my manifest.yml and Staticfile. When I tried to do a cf push within the dist/AppName directory, everything worked as expected. However, I want ...

How can I trigger a click event with Ionic's ion-toggle and radio-group components

I am currently using Ionic3 and I would like to implement an HTML element (ion-toggle and radio-group) that triggers a JavaScript function upon clicking. As you can observe below, I have included an attribute ng-click as per the guidance provided here, bu ...

Trouble shooting: Angular 2 Http get request not firing

I'm facing an issue where nothing happens when I try to subscribe to my observable. There are no errors in the console or during the build process. Below is the code snippet that I am using: My service getBlueCollars(): Observable<BlueCollar[]& ...

Angular's observable function is not providing a complete response

In my Angular component, I have a function that is called from a template. This function returns an Observable of type string, but unfortunately it only returns the `data` variable. How can I modify it to return `dateNew[0] + " de " + data + " de "+ dateNe ...

What is the best way to transfer an array to a different component?

I have an array called FidId that consists of strings, and I am looking to pass this array to another component for use. public AddSelection(layer: VectorLayer, map:Map){ this.vectorSource = layer; //start select var FidId:string[] = []; ...

Optimize Next.js 10 TypeScript Project by Caching MongoDb Connection in API Routes

I am currently in the process of transitioning next.js/examples/with-mongodb/util/mongodb.js to TypeScript so I can efficiently cache and reuse my connections to MongoDB within a TypeScript based next.js project. However, I am encountering a TypeScript err ...

JavaScript heap runs out of memory in Angular testing because of extensive mock data

While working on testing in angular 4, I encountered a need for large amounts of data in my test cases. Specifically, I needed to dynamically require JSON files in my spec files, each ranging from approximately 4 to 5 MB. As part of the process... it(& ...