userlkjsflkdsvm
userlkjsflkdsvm

Reputation: 983

Hide and Show item on click stored in multiple arrays - ionic 2+ / angular 2+

The issue I have is not displaying the show and hide functionality. The issue is being able to grab the correct index for the selected button. Below I am grabbing the index of the second array. If the user were to select the first item of each of the currentItems array, all of the first items would open and close. All I want is the one that is selected to close and open. On click of the resultInfo array I would like the itemInfo to display.

HTML

 <div *ngFor="let a of currentItems">
    <ion-item-sliding id="rightdiv" *ngFor="let b of a.resultInfo; index as i">
      <button ion-item (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}" class="destInfo">
        <h3>click me</h3>
      </button>
      <ion-item [class.hidden]="!isGroupShown(i)" *ngFor="let c of b.itemInfo">
        <ion-label>{{c.name}}</ion-label>
      </ion-item>
    </ion-item-sliding>
    </div>

TS

shownGroup = null;

toggleGroup(group) {
  if (this.isGroupShown(group)) {
    this.shownGroup = null; 
  } else {
    this.shownGroup = group;
    console.log(this.shownGroup, 'SHOWN GROUP HERE')
  }
}
isGroupShown(group) {
  return this.shownGroup === group;
};

DATA

currentItems = [
  {
    "time": "a some time",
    "resultInfo": [
      {
        "about": "some place",
        "itemInfo": [
          {
            "name": "someName"
          },
        ]
      }
    ]
  },
  {
    "time": "some time",
    "resultInfo": [
      {
        "about": "some place",
        "itemInfo": [
          {
            "name": "someName"
          },
        ]
      }
    ]
  }
]

Upvotes: 1

Views: 1492

Answers (1)

FAISAL
FAISAL

Reputation: 34691

You need to save state of individual items. Currently you just set one variable which toggles all the groups.

In your ts, add a variable to store every item's state:

toggleGroups: any = {};

Remove the toggleGroup() and isGroupShown() methods, you don't need them.

Change your html to following:

<div *ngFor="let a of currentItems; index as i">
    <ion-item-sliding id="rightdiv" *ngFor="let b of a.resultInfo; index as j">
        <button ion-item 
                (click)="toggleGroups['group'+i+'_'+j] = !toggleGroups['group'+i+'_'+j]" 
                [ngClass]="{active: toggleGroups['group'+i+'_'+j]}" class="destInfo">
            <h3>click me</h3>
        </button>
        <ion-item [class.hidden]="!toggleGroups['group'+i+'_'+j]" 
                  *ngFor="let c of b.itemInfo">
            <ion-label>{{c.name}}</ion-label>
        </ion-item>
    </ion-item-sliding>
</div>

Here is a link to Stackblitz Demo.

Upvotes: 2

Related Questions