nlr_p nlr_p - 2 months ago 23
TypeScript Question

How to change the button property dynamically in angular2

Template,

<div *ngFor="let detail of details" class = "col-sm-12 nopadding">
<a class="button buttonaquacss button-mini button-aqua
text-right pull-right" [ngClass]="{activec: color}"
(click)='sendrequest(button,detail._id)'
#button [ngStyle]="{'background-color': color}">{{buttonname}}
</a>
</div>


My ts,

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

buttonname = 'pending';
this.color = true;
}

});
}


The proflem is when I click on one button all the button properties are getting changed to pending can anyone give a suggestion please.

Answer

Because there is only a single buttonname variable and all buttons bind to the same. You need to bind them to different variables. Either you use a different variable name for each button or you use 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;
        }
    });
}
Comments