Ways to dynamically update button properties in Angular 2

Customized Template,

<div *ngFor="let item of items"  class = "col-sm-12 nopadding">
  <a  class="button buttonaquacss button-mini button-aqua  
      text-right pull-right" [ngClass]="{activec: isActive}" 
      (click)='updateStatus(item)' 
      #btnElement [ngStyle]="{'background-color':  backgroundColor}">{{buttonLabel}}
  </a>   
</div>

My custom TypeScript code,

buttonLabel = 'connect';
updateStatus(button): void {
    this.http.post('http://localhost:3000/updatestatus', formdata, { headers: headers })
        .subscribe(
        response => {
            if (response.json().status == 'success') {

                this.isActive = true;
                this.backgroundColor = 'blue';
            }

        });
}

The issue occurs when clicking one button affects all buttons, seeking suggestions to resolve the problem.

Answer №1

To avoid conflicts with the buttonname variable, it is important to bind each button to a unique variable. This can be achieved by either using different variable names for each button or utilizing an array of values.

<a (click)='send(button,detail._id)' #button>{{buttonname[detail._id]}}</a> 
buttonname = {'id1': 'connect', 'id2': 'connect'};

sendrequest(button, index): void {
  this.http.post('http://localhost:3000/sendrequest', formdata, { headers: headers })
    .subscribe(
    response => {
        if (response.json().status == 'success') {
            buttonname[index] = 'pending';
            this.color = true;
        }
    });
}

update

<a (click)='send(button,detail._id)' #button>{{pendingId == detail._id ? 'pending' : 'success'}}</a> 
pendingId;

sendrequest(button, index): void {
  this.pendingId = index;
  this.http.post('http://localhost:3000/sendrequest', formdata, { headers: headers })
    .subscribe(
    response => {
        if (response.json().status == 'success') {
            pendingId = null;
            this.color = true;
        }
    });
}

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

Storing data from a collection of interface objects in a string array

Take a look at the following code snippet: import React, {FC} from 'react'; import {useFetchErrors} from "../Api/Api"; import {useLocation} from "react-router-dom"; interface ExecutionTableProps { project_id: number } const ...

The Angular 2 routerLink doesn't update the component after the initial click, even though the URL changes in the browser

When using Angular 2, I encountered an issue where clicking a routerLink in the App module successfully navigates to a parameterised route (e.g. /events/2) and loads the correct component (event-details) on the initial click. However, subsequent clicks on ...

Angular2 URL fragment not recognized in Firefox

My website's main page is divided into different sections: Introduction Services Projects All the content is on the same page. To navigate to a specific section, I use Angular2 fragments in my navigation structure. Here's the HTML snippet for ...

Save the application's state of the user in a mean stack program

In my Angular 9 application, I have forms with multiple sections. The first section includes name and personal details, the second part covers primary school information, and the third part focuses on past jobs held by the user. Each part is displayed in a ...

What could be causing the import alias issue in the latest version of Next.js, version 12

Below are my CompileOptions: { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": false, "skipLibCheck": tr ...

Best practice for incorporating the cq-prolyfill third-party JavaScript library into an Angular 5 application

I'm experiencing an issue with the cq-prolyfill library not functioning properly when included through a typescript import statement within an angular module. I have confirmed that it is included in my vendor bundle, but for some reason the initial se ...

Exploring ways to incorporate conditional imports without the need for personalized webpack settings!

Our project is designed to be compatible with both Cordova and Electron, using a single codebase. This means it must import Node APIs and modules specific to Node for Electron, while ignoring them in Cordova. Previously, we relied on a custom webpack con ...

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

Aggregating all elements in an array to generate a Paypal order

I'm currently working on a React project where I need to integrate the PayPal order function and include every item from an array. Below is my code snippet, but I'm struggling with how to achieve this: export default function Cart(): JSX.Element ...

What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typ ...

How can I gather information from members who have already signed up?

I have a form that submits data to the Angular Firebase database. Once the form is submitted, I want to display the previously submitted data in the form if the user signs in again. Below is my .ts file: import { Component, OnInit } from '@angular/c ...

How to bring in a module from another package in Angular 4

This is a fundamental query. As an individual just starting with Angular and npm, this may seem like a basic question for some. However, despite extensive research, I haven't been able to find a solution. Before embarking on a project, I want to cre ...

Encountering an "Invalid parameter: redirect_uri" error in Keycloak while manually refreshing the page

This is an Angular 17 single-page application utilizing the latest version of keycloak-angular (15.2.1 at the time of writing). I'm facing a perplexing issue where after successfully authenticating and logging out, if I reload the page, it breaks enti ...

Discovering the interface type of class properties in order to implement a factory method

I am struggling with implementing a factory method in my code. I want to be able to pass not only a Class type to instantiate but also a set of default values for the properties within the class. My goal is to have the compiler notify me if I try to pass i ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...

Tribal Code Typescript Compiler

Typescript is a great alternative to Javascript in my opinion, but it bothers me that it requires node.js as a dependency. Additionally, I find it frustrating that there seems to be only one compiler available for this language, and it's self-hosted. ...

Modifying the value of an observable in a component does not automatically activate the subscribe function in a service

In my current situation, I am facing an issue where data sent from a component to a service for manipulation is not triggering the desired behavior. The intention was to update a BehaviorSubject variable in the service by using the next method when fetchin ...

Looking for a way to validate all form fields even when only one field is being used?

In Angular 8, I am facing an issue where the current validation only checks the field being modified. However, there are some fields whose validation depends on the values of other fields. Is there a way to make Angular recheck all fields for validation? ...

Do I have to wait for the HTTP get request to access the fetched object property?

I am currently working with Angular and TypeScript on a dish-detail component that is accessed through 'dishes/:id' The dish object returned has a property called components, which contains an array of objects with two properties: id: type stri ...

What is the best approach for implementing line coverage for object literal in Typescript Mocha unit-tests?

Lead: I am a newcomer to using typescript and writing unit tests with Mocha and Chai. Question: Can anyone provide tips on achieving 100% line coverage in unit tests for an object literal that isn't within a class? I want to avoid going static if pos ...