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

gulp-angular2 task is malfunctioning

Currently, I am in the process of working on a gulpfile and have written the following task: var tsProject = ts.createProject('app/Resources/public/angular/tsconfig.json'); gulp.task('angular-2', function () { var tsResul ...

What is the best way for a function to accommodate various types that adhere to an interface?

How can we create a function that can accept multiple types with a common interface? Let's consider the example: interface A {a: number} type B = {b: string;} & A type C = {c: string;} & A function acceptA(a: A) { return a } acceptA({a ...

In Angular 2, you can include a routerLink in a child component that directs to the root

Currently, I am developing a web application using Angular 2 Beta 8 and encountering an issue with nested routes while utilizing the routerLink directive. The structure of the router is as follows: AppCmp |-> NewItemFormCmp |-> UserDashboardCmp ...

Utilizing PrimeNG's p-dataView feature without repetitive FieldSets

Currently, I am utilizing p-dataView and I'm interested in implementing p-fieldset based on the application type. My goal is to prevent the fieldset from being duplicated when multiple instances occur. The scenario below illustrates one such case; how ...

The DHTMLX Gantt tool is throwing an error message saying "TS6137: Type declaration files cannot be

Lately, I've noticed some issues with my code that were not present before. It seems like something may have changed in either typescript or dhtmlxgantt. Whenever I compile the code, I keep running into these errors: Error TS2306: File 'project ...

Should loaders be utilized in an Angular application?

Webpack configuration allows the use of various loaders, such as file-loader, html-loader, css-loader, json-loader, raw-loader, style-loader, to-string-loader, url-loader, and awesome-typescript-loader. Does Angular have built-in knowledge of loaders with ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...

Encountering the issue: "Error: The mat-form-field must include a MatFormField

Working on an Angular form, attempting to validate a reactive form with Material design template. Encountering an error when trying to use ngIf condition for validation in the textbox: Error: ERROR Error: mat-form-field must contain a MatFormFieldContr ...

Updating parent components through child components in ReactWould you like another unique

In my current project, I am attempting to change the state of the main component labeled App.tsx by using a child component called RemarksView.tsx. I have attempted passing props such as setRemarks and remarks, but unfortunately the state in the parent c ...

Is there a way to ensure that in React (Typescript), if a component receives one prop, it must also receive another prop?

For instance, consider a component that accepts the following props via an interface: interface InputProps { error?: boolean; errorText?: string; } const Input = ({error, errorText}: InputProps) => { etc etc } How can I ensure that when this com ...

Unable to determine the data type of the property within the table object

Is it feasible to retrieve the type of object property when that object is nested within a table structure? Take a look at this playground. function table<ROW extends object, K extends Extract<keyof ROW, string>>({ columns, data, }: { col ...

Angular 13: Problems arise with custom theme in Angular Material version 13

I've set up a custom theme palette for my project that works perfectly with version ^12.2.13 of Angular Material, but not with ^13.2.3. Here's the SCSS code for my custom theming: my-custom-theme.scss @import '~@angular/material/theming&apo ...

What is the best way to change the name of an imported variable currently named `await` to avoid conflicting with other variables?

Here is the given code snippet: import * as fs from 'fs'; import {promises as fsPromises} from 'fs'; // ... // Reading the file without encoding to access raw buffer. const { bytesRead, buffer as fileBuffer } = await fsPromises.read( ...

Checking to see if a string meets the criteria of being a valid ARGB value

How do I verify that a string represents a valid ARGB value, such as #ffffffff for ARGB 255,255,255,255? Is there a way to validate this using TypeScript and C#? ...

"Sequencing http.get requests in Angular 2 using

In my service, I have a series of http.get requests structured as follows: constructor(private http:Http) {} getDetails(sysID:string){ var details; this.http.get('https://blahURL').map(res => res.json().filter(f => f.id == another.id)[0] ...

Protractor Jasmine experiencing issues with describe block within the it block

I am currently exploring Jasmine and attempting to incorporate shared steps in my test cases. I want to reuse certain steps between two scenarios, but when I try to execute a common describe block inside an it block, it does not run as expected. Here is a ...

Creating a custom directive in Angular that dynamically applies attributes based on the current route

I have been able to successfully set the attribute data-toggle-state to both active and inactive using the following code: <a [routerLink]="['/home']" [attr.data-toggle-state]="router.isActive('/home', true) ? 'active' : ...

Angular 7/8 now allows for empty strings in Template Driven Forms

I've encountered a problem with my form validation that allows empty strings. The required attribute works, but it still allows the user to input spaces. I came across a solution online which involves using ng-pattern with the pattern pattern=".*[^ ]. ...

Issue with React filter function where data is not being displayed when search query is left

I am facing an issue where the data does not show up when the search term is empty. Previously, I used to have this line in my code if (!searchTerm) return data for my old JSON data, and it worked fine. However, now that I'm using Sanity CDN, this lo ...

Is there a way to obtain a unique response in TestCafe RequestMock?

With Testcafe, I have the capability to simulate the response of a request successfully. I am interested in setting up a caching system for all GET/Ajax requests. The current setup functions properly when the URL is already cached, but it fails to prov ...