1

I am facing an issue with the nested iteration, Suppose I have one button in child loop and i want index of parent and child loop both in onclick function of JS file.

I am only getting index of child loop through event.target.value. Not sure how to get index of parent.

2
  • Putting your event handler on the parent should allow events from the children to bubble up and be captured at the parent. There are several articles on JS event propagation and LWC events if you search for "event bubbling" or "event propagation". Can you share what code you currently have?
    – nbrown
    Sep 16, 2020 at 15:44
  • Thanks for the response @nbrown, data attributes fixed the issue. Sep 16, 2020 at 16:40

1 Answer 1

2

You can use data attributes to pass in extra information. Here's a simple playground:

<template>
    <div key={outer.key} for:each={data} for:item="outer" for:index="outerIndex">
        Outer key: {outer.key}
        <div onclick={handleClick} key={inner} for:each={outer.data} for:item="inner" for:index="innerIndex">
            Inner Item: {inner}
            <button data-outer={outerIndex} data-inner={innerIndex}  onclick={handleClick}>Select</button>
        </div>
    </div>
    <hr />
    Output:
    {output}
</template>

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {
    data = [
        {key: 0, data:[1,2,3]},
        {key: 1, data:[4,5,7]},
        {key: 2, data:[7,8,9]},
    ]
    output;
    handleClick(event) {
        let outer = event.target.dataset.outer;
        let inner = event.target.dataset.inner;
        this.output = `${outer}/${inner}`;
    }
}

WebComponents demo

1
  • Thanku so much @sfdcfox, you saved my day :) Sep 16, 2020 at 16:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .