Angular 2 feature that allows for a single list value to be toggled with the

Currently, my form is connected to a C# API that displays a list of entries. I am trying to implement a feature where two out of three fields can be edited for each line by clicking a button that toggles between Yes and No. When the button is clicked, it should update values.excludeMrbxfer from 0 to 1 (I have created a custom pipe to display Yes for 1 and No for 0) or vice versa. The code snippet below shows how I am displaying the list with the toggle button.

<tr *ngFor= 'let value of values' >
    <td class = "align-left"  >{{value.binId}}</td>
    <td > {{value.excludeMrbxfer | yesNo}}
                        <button type="button" class="btn btn-primary" name='excludeMrbxfer' 
                        [(ngModel)] = "values.excludeMrbxfer" (click)='toggleChange(values)'>
                        {{value.excludeMrbxfer | yesNo}}</button>  
    </td>
</tr> 

The problem I am facing is that when the button is clicked, it changes the values for all items in the table instead of just one. The desired functionality is to modify the state of only one item at a time.

Another issue I am encountering is regarding the toggleChange() method where I have to specifically mention which element in the JSON array needs to be edited for it to work. This results in changing all values.ecludeMrbxfer values when I intend to change only one. Below is the implementation of the toggleChange() method in my component:

toggleChange(values: any) {
  if (values[0].excludeMrbxfer === 1) {
    values[0].excludeMrbxfer = 0;
  } else if (values[0].excludeMrbxfer === 0) {
     values[0].excludeMrbxfer = 1;
  }
}

Answer №1

When creating your template, be sure to loop through the values array using *ngFor="let value of values". This way, you can pass each individual value into (click)="toggleChange(value)" instead of passing in the entire array.

<td> 
    {{value.excludeMrbxfer | yesNo}}
    <button type="button" class="btn btn-primary" name="excludeMrbxfer" 
            [(ngModel)] = "value.excludeMrbxfer" (click)="toggleChange(value)">
        {{value.excludeMrbxfer | yesNo}}
    </button>  
</td>

By making this change, your toggleChange() function will receive a single value as input.

toggleChange(value: any) {
  if (value.excludeMrbxfer === 1) {
    value.excludeMrbxfer = 0;
  } else if (value.excludeMrbxfer === 0) {
     value.excludeMrbxfer = 1;
  }
}

Answer №2

To fix the issue, I made a modification by including an index in the *ngFor loop within the table row. This index was then passed to the toggleChange() method located in my component.

<tr *ngFor='let value of values; let i = index' >
                    <td class="align-left">{{value.binId}}</td>
                    <td>
                        <button type="button" class="btn btn-primary" name='excludeMrbxfer' 
                        [(ngModel)]="values.excludeMrbxfer" (click)="toggleChange(values,i)">
                        {{value.excludeMrbxfer | yesNo}}</button>  
                    </td>

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

Can you define the type of binding value in AngularJS 1.5(6) using TypeScript?

I am looking to define the type of binding items so that I am able to utilize components similar to functions. For instance, consider a component: angular.module('app').component('navBar', new NavBar()); class NavBar{ public bin ...

Angular 13: A guide on pulling data from an Excel spreadsheet

I have been encountering issues while trying to display data from a CSV file on a web platform using Angular 13. The errors I am facing are related to binding 'ngModel' and type mismatches in the code. errors Error: src/app/app.component.html:24 ...

Employing a boolean constant to verify if a parameter has been specified

Struggling with TypeScript version 2.8.3, I'm confused as to why the code below is failing to recognize that params is defined inside the if block. const testFunction = (params?: string) => { const paramIsDefined = typeof params !== 'undefi ...

The assertion error `args[3]` must be an integer value, but it failed to meet the requirement

Software Version: v12.19.0 Operating System Platform: Linux ayungavis 5.4.0-48-generic #52~18.04.1-Ubuntu SMP Thu Sep 10 12:50:22 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux Subsystem: Steps to Reproduce the Issue I attempted to follow the tutorial provided ...

Angular Github Deployment Issue: Page malfunctioning as a result of strict-origin-when-cross-origin restriction

I am currently learning Angular and attempting to deploy it on Github Pages. However, I have encountered an issue where the app is not functioning properly. After inspecting the page, I discovered a CORS origin error when trying to access certain resource ...

Creating an OpenLayers map within an Ionic component

Implementing Ionic v4 with OpenLayers v5.3 I am facing an issue while trying to display an OL map as a component in my project. Only the icons are being loaded and it seems like the styles and JS configuration are not loading properly. I have tried inject ...

Using spyOn to fake Observable responses - a step-by-step guide

My service is set up to request JSON data through HTTP: export class TodosService { constructor(private http: HttpClient) {} getTodos(): Observable<any> { return this.http.get<any>('https://jsonplaceholder.typicode.com/todos') ...

Using Arrow Functions in Angular 2 Typescript with Support for IE11

Are arrow functions in Typescript for Angular2 compatible with IE 11? I have come across information stating that arrow functions in javascript may not be supported in IE 11, but I am uncertain if the same applies to Typescript. ...

I am encountering an issue where the nested loop in Angular TypeScript is failing to return

I am facing an issue with my nested loop inside a function. The problem is that it is only returning the default value of false, instead of the value calculated within the loop. Can someone please point out what I might be doing incorrectly? Provided belo ...

Filter through the array using the cast method

Trying to implement this: let selections = list.filter(obj => obj.type === "myType"); An issue arises with the filter function displaying an error message which states 'filter' does not exist on type 'NodeType' I attempted to ...

Achieving successful npm caching in Azure DevOps for a .net core Angular project

I have a project for a client that involves building an Angular 10/.Net Core project, and it currently takes around 15 minutes. I've been experimenting with caching to optimize the process. Despite trying different configurations, when I add eq(variab ...

What is the most effective method for integrating Bootstrap CSS into an Angular project?

When incorporating a Bootstrap CSS file into an Angular project that has already been added using yarn add <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2909d9d868186809382b2c6dcc3dcc3">[email protected]</a>, th ...

Implementing Angular2 Service into component's base class

Looking to create a base class that can perform common tasks for components throughout their life-cycle. Need this base class to have access to a service as well. How can I inject it? While using a singleton instead of a service is an option, it may not al ...

Reactive sidenav in action with Angular

Exploring the creation of a reactive component for educational purposes, disregarding project structure =). My directory layout: app.component.html <app-header></app-header> <app-sidenav></app-sidenav> <app-footer></app ...

When an input event is dispatched in a unit test, the value changes of a form are not activated

Currently, I am testing a scenario where I need to verify if a value changes on the form when input is typed in. This particular project utilizes Nrwl nx as well as jest for testing purposes. The component code snippet is as follows: export class InputNu ...

Is there a way to modify the default lite-server port in the Angular quickstart setup?

I recently obtained the Angular 4 quickstart app and decided to modify the default lite-server port by including "port": 8000 in bs-config.json like this: { "server": { "port": 8000, "baseDir": "src", "routes": { "/node_modules": "node ...

Error encountered during Angular upload using Asp.net core: System.Text.DecoderFallbackException is thrown when bytes [FF] cannot be translated at the specified index

I am having trouble uploading a file using Angular 7 and Asp.net core 2.2 I have set up the Angular web service to append the file and include a property Name. However, when I call the WebService from Angular, I encounter an error in the Asp.net core l ...

The automatic type inference in Typescript is faulty

I am currently working with TypeScript version ^4.1.3 and have developed a REST API that deals with albums and art collections. Before sending the response to the web client, I make sure to remove the userId property from the collections. Below are my Alb ...

Leveraging external modules within Angular 2 to enhance component functionality

I have developed a custom module called ObDatePickerModule, which includes a directive. In addition, I have integrated the ObDatePickerModule into a project by including it in the dependencies section of the package.json. Now, I am importing Module A i ...

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...