Jason Bullen
Jason Bullen

Reputation: 155

ionic how to identify clicked button in a *ngFor loop

I am creating a list of text and buttons. I want to identify which button has been clicked in the clicked function.

HTML

<ion-list>
    <ion-item ion-item *ngFor="let act of questions.test">
      {{act.quote}}
      <ion-item>
        <button large ion-button item-right (click)="SelectClicked()">Select</button>
      </ion-item>
    </ion-item>
</ion-list>

TS

  this.questions =
  {
    "test":[
    {
      "quote": "first row"
    }, {
      "quote": "second row"
    }, {
      "quote": "third row"
    }, {
      "quote": "fourth row"
    }
    ]
  }


SelectClicked(detail){
//please help
// which button was clicked ( 1 to 4 ) ?
  console.log("SelectClicked" + detail);
}

Upvotes: 3

Views: 4500

Answers (2)

Shane
Shane

Reputation: 3199

I am guessing that you want the selected element, that can be done by passing on the event to the handler.

<button (click)="SelectClicked($event)"></button>

Which you can fetch the element from the event with using event.target, event.srcElement or event.currentTarget.

But if you mean to pass along the index or the item of your array, you can just pass on that act object or add an index to the loop...

<ion-item ion-item *ngFor="let act of questions.test; let i = index">

...and pass on the object...

<button (click)="SelectClicked(act)"></button>

...or the id

<button (click)="SelectClicked(i)"></button>

Upvotes: 5

Sathyajith
Sathyajith

Reputation: 4024

You can pass the "act" value as a parameter to the function like this

 <button large ion-button item-right 
  (click)="SelectClicked(act)">Select
 </button>

Upvotes: 0

Related Questions