0

so I'm trying to create multiple checkboxes based on the number of decks I have.
In this example, one of the decks is called fruit. these checkboxes look like:
enter image description here

so if a user presses the fruit button, all fruit objects are checked. if a user presses a single button, that fruit will get marked.

But if I selected all fruits with the fruit button and then remove a single fruit like kiwi. it deletes it from the list entirely, but I just want to uncheck them:

Example:

But if I check a single object and uncheck that object, the problem is not occurring.

Example:

Here is my stack blitz link: https://stackblitz.com/edit/angular-ivy-pwgfng?file=src/app/app.component.ts
If someone would like to take a look at it.

If you have any questions, just ask. I'm happy to reply.

1 Answer 1

1

The problem is with reference to array.

When you select deck which isn't in chosenDecks yet this code run:

this.chosenDecks.push(selectedDeck);

so an deck from allDecks is being added along with array reference.

Later on you splice types array when an fruit is unselected:

this.chosenDecks[deckIndex].types.splice(typeIndex, 1);

Solution to prevent removing that fruit from this.allDecks array is:

this.chosenDecks.push({...selectedDeck, types: selectedDeck.types.slice()});

or any other that will copy array without reference :-)

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

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.