Home > Back-end >  Angular Toggle values in array changes position
Angular Toggle values in array changes position

Time:07-05

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?

CodePudding user response:

<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();
}

CodePudding user response:

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).

  • Related