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

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

Exploring TypeScript: Navigating the static methods within a generic class

I am trying to work with an abstract class in TypeScript, which includes an enum and a method: export enum SingularPluralForm { SINGULAR, PLURAL }; export abstract class Dog { // ... } Now, I have created a subclass that extends the abstract cla ...

Retrieve an instance of the property class within a property decorator

I'm attempting to create a decorator called @Prop that will assist me in adjusting attributes for custom elements. This is the desired code: class MyCustomClass extends HtmlElement { get content() { return this.getAttribute('content&apo ...

What is the definition of reusable components within the context of Angular, React, and Vue?

I've been hearing a lot about reusable components. What does this actually mean? For instance, if I want to showcase basic user information like ID, name, age, etc. Does it imply that the component is "plug and play," where you simply write the sele ...

The customer's status cannot be determined

I've encountered an issue with my TypeScript code that includes a simple if-else logic. endDate: String = ''; customerStatus: String; this.endDate = this.sampleData.customerStartDate; if (this.endDate == null) { this.customerStatus = ' ...

Retrieve a specific value from the NGXS state by providing a parameter

I have a unique situation where my state contains JSON data like this: {id: "1", name: "ig1", description: "ig 11"} {id: "5", name: "hhh", description: "hhh"} {id: "6", name: "ggg", description: "hhh"} My goal is to specifically extract the data for id = ...

Error: Angular router outlet could not find any matching routes for the requested

I have been working on an application that utilizes lazy-loaded modules for each main section of the app. In one module, I have two router outlets - a primary one and one called details. const routes: Routes = [ { path: '', component: BooksCo ...

Is there a way to merge TypeScript code with C++ during compilation?

Currently, I have a project written entirely in C++. However, there is an additional file written in typescript because I couldn't find equivalent libraries in C++. This typescript file performs the following actions: It contains a typescript CLI cod ...

When attempting to access Firebase Storage with Angular, you may encounter the error message: "TypeError: app.storage

Having trouble connecting my Angular app to FireBase. The component appears blank and the Chrome console is showing a 'TypeError: app.storage is not a function'. Any ideas on what I might be doing wrong? Thanks in advance. ng --version Angular C ...

Changing the target in tsconfig.json to "es2022" leads to the error message "Property 'xx' is referenced before its initialization.ts(2729)"

My Angular code is filled with instances where I assign a property at its definition like this... public data$ = this.service$.fetchData; constructor(private service$: MyService However, after updating my tsconfig.json target to "es2022", I encountered ...

In the Angular Google Maps API, is it possible to update the attributes of <agm-marker> directly within the TypeScript code?

Currently, I am fetching markers from the database and displaying them on a map using Angular Google Maps (AGM) by utilizing the <agm-marker> tag. In my code snippet below, you can see how I fetch and store the markers in an array named markers in t ...

Creating a universal timer at the application level in Angular

Is there a way to implement a timer that will automatically execute the logout() function in my authentication.service at a specific time, regardless of which page I am currently on within my application? I attempted to create a timer within my Authentica ...

Unable to set up enzyme adapter

Currently, I am in the process of setting up the enzyme adapter for testing purposes. The code snippet that I have is quite straightforward: import * as enzyme from 'enzyme'; import * as Adapter from 'enzyme-adapter-react-16'; enzyme. ...

Getting a string output from a Typescript promise

Here is some Typescript code that I thought would be simple. public showDialog(theNickname: string): string { var req = { method: 'POST', url: '/Q/GetUserDetails', data: { nickname ...

Looking for a shortcut in VSCode to quickly insert imports into existing import statements or easily add imports as needed on the go?

It seems that the current extensions available on the VSCode marketplace struggle to properly add Angular imports. For example, when I try to import OnInit using the Path IntelliSense extension: export class AppComponent implements OnInit It ends up impo ...

Issue with displaying international characters when using HttpClient's http.get() function in Angular.The

I am facing an issue that I can't quite figure out as I am new to Angular. My goal is to read a local .csv file and display its contents in a table. Everything seems to be working fine, except for the fact that when special characters like "č, ć, š ...

What could be causing my TypeScript project to only fail in VScode?

After taking a several-week break from my TypeScript-based open-source project, I have returned to fix a bug. However, when running the project in VScode, it suddenly fails and presents legitimate errors that need fixing. What's puzzling is why these ...

How can I redirect a remote image URL to a local folder during development?

Currently, I am pulling image URLs from a database that was dumped from the production server. An example of one of these URLs is https://example.com/imageStorage/photo.jpg. These URLs are then used to display images in HTML templates using the following f ...

Why is it that the Jasmine test is unsuccessful even though the 'expected' and 'toBe' strings appear to be identical?

I have been developing a web application using Angular (version 2.4.0) and TypeScript. The application utilizes a custom currency pipe, which leverages Angular's built-in CurrencyPipe to format currency strings for both the 'en-CA' and &apos ...

Jest tests are failing to render React IonDateTime component

While executing Jest on an Ionic React component, I encountered a test failure consistently, regardless of whether the component had a time value or not. test('IonDateTime display', () => { render(<IonDatetime data-testid="foo" ...