3

I've got a button element in an *ngFor array in my Angular2 app.

The structure of the button is:

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

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

When I click on it I need to remove the text inside the span .text and put smth else inside, say <span class="text"> Added! </span> not display the .price 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?

3
  • 3
    instead of isPressed use a semantic variable like product.isAdded. This way the state of the button is bound to the product in question. Commented Feb 7, 2017 at 10:35
  • Why it's not working with isPressed, but works well with isAdded? Please, submit your answer thus I could vote for your help Commented Feb 7, 2017 at 10:48
  • The reason is not the wording, but the product, which refers to a specific object the button relates to. There's many products (that's why you need the loop) and therefore you have the state saved per product. Each button shows the state of one particular product. If you were using a generic variable like isPressed there is only one and all buttons are watching it. The answers below show you how to adjust your code. Upvote them :-) Commented Feb 7, 2017 at 10:57

2 Answers 2

2

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>
</button>

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

Sign up to request clarification or add additional context in comments.

Comments

2

As suggested in comments you should keep selected flag on product item itself. This way you can do something like this in template:

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

And in controller:

selectProduct(product) {
  // You probable want to make HTTP request here to save product
  // and on success set selected flag, or do something else..
  product.selected = !product.selected
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.