0

I have an array with 4 values which I toggle (remove and Add to the array).

selectedSections: any[] = ['one', 'two', 'three', 'four'];

Then I have a button which I would click to make each selected appear and disappear.

<button (click)="toggleVal('one')">Toggle One</button>
<button (click)="toggleVal('two')">Toggle Two</button>
<button (click)="toggleVal('three')">Toggle Three</button>
<button (click)="toggleVal('four')">Toggle Four</button>

My issue is that the function below does the toggle job greatly but I need to be able to make the values appear back into the same position that they are now. At the moment everytime a value is added it's added to the end and I need to either be able to specify what position I want it added to or a way to make them stay in position.

Here is the code below:

toggleVal(val: any) {
    if (this.selectedSections.includes(val)) {
      let index = this.selectedSections.indexOf(val);
      this.selectedSections.splice(index, 1);
    } else {
      this.selectedSections.push(val);
    }
    this.howMany();
    this.filterData();
}

How can I get it to do this?

2 Answers 2

1
<button (click)="toggleVal('one', 1)">Toggle One</button>
<button (click)="toggleVal('two', 2)">Toggle Two</button>
<button (click)="toggleVal('three', 3)">Toggle Three</button>
<button (click)="toggleVal('four', 4)">Toggle Four</button>

toggleVal(val: any, i: number) {
if (this.selectedSections.includes(val)) {
  let index = this.selectedSections.indexOf(val);
  this.selectedSections.slice(index, 1);
} else {
  this.selectedSections.splice(i, 0, val);
}
this.howMany();
this.filterData();
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can pass index value you want with your function in your html. Then you can use: arr.splice(index, 0, item);

It will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

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.