0

I'm currently making a small app to practice TypeScript and Angular. I have an array of numbers.

var numbers = [9, 10, 11, 14, 13];

I have a set of buttons, i'm looping over, each is associated to a number, what I want to accomplish is when I click one of the buttons, its number gets added to or removed from the array, depending on its starting state.

each number should only exit once.

2
  • 2
    Have you tried anything? It's a good exercise in using .splice, .push, and loops that sounds like a homework assignment. Commented Dec 28, 2017 at 17:27
  • buttons are independent, if the number exists in the array, I add I toggle a class. Commented Dec 28, 2017 at 17:47

2 Answers 2

1

The following is an example of accessing data about the button that is clicked. Not sure what you meant by "state" but adding an removing an array item based on some particular logic should be trivial.

|-- component.html

<button id="1" (click)="onClick($event)">B1</button>
<button id="2" (click)="onClick($event)">B2</button>
<button id="3" (click)="onClick($event)">B3</button>

|-- component.ts

onClick(event) {
  var target = event.target || event.srcElement || event.currentTarget;
  var idAttr = target.attributes.id;
  numbers.push(idAttr);
}
Sign up to request clarification or add additional context in comments.

1 Comment

by state I meant if the number or ID is already in the array I don't want to add it again
1

I think the we need to change the onClick function mentioned by @Wallace to this:

onClick(event) {
  var target = event.target || event.srcElement || 
event.currentTarget;
  var idAttr = target.attributes.id;
  numbers.indexOf(idAttr) === - 1 && numbers.push(idAttr);
}

This will add the number in idAttr to the numbers array only if it is not already present in the array.

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.