Alexandr Belov Alexandr Belov - 2 years ago 111
TypeScript Question

Change button appearance on click Angular2

I've got a button element in an

array in my Angular2 app.

The structure of the button is:

<span class="price">{{ product.price }}</span>

<span class="text"> Add me! </span>

When I click on it I need to remove the text inside the span
and put smth else inside, say
<span class="text"> Added! </span>
not display the
span interpolation.

I tried to make it in the following way:

<button [textContent]="isPressed? 'Added!' : 'Add me' "></button>

And declare the corresponding property in the Class like:

private isPressed = false;

It works fine, but the problem is that it changes all buttons simultaneously, and I need to change only the clicked one.

What is the correct way to make it working properly?

Answer Source

You will probably store added products somewhere anyway. Use this information to display proper button label, e.g.:

<button (click)='addProduct(product)'>
   <span class="price" *ngIf="!isProductAdded(product)">{{ product.price }}</span>
   <span class="text">{{ isProductAdded(product) ? 'Added!' : 'Add me!'}}</span>

addProduct(product) and isProductAdded(product) would need to be defined in your Component.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download