1

I have a dynamic lwc that generates related lists dynamically. I want to add a New button to the component but want to be able to dynamically get the component from which the new button was clicked so I can get the current object as a property. How do I achieve this or is this not possible in this manner or another way?

Something like:

createNew() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: event.button.cmp.obj,
                actionName: 'new'
            }
        });
    }

Thanks in advance.

1 Answer 1

4

Consider using dataset to dynamically get the custom attribute of components in iteration.

HTML

<template>
    <template for:each={OBJECTS} for:item="obj">
       <lightning-button key={obj} variant="brand" label="New" title="New" onclick={createNew} data-object={obj}></lightning-button>
    </template>
</template>

JS

import { LightningElement} from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

const OBJECTS = ['Account', 'Contact', 'Lead'];

export default class Navtab extends NavigationMixin(LightningElement) {
    createNew(event) {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: event.target.dataset.object,
                actionName: 'new'
            }
        });
    }
}
2
  • Thanks for your answer bit I get the error: Missing key for element <lightning-button> inside of iterator. Elements within iterators must have a unique, computed key value.
    – Thomas
    Commented Nov 18, 2021 at 9:52
  • @Thomas I've updated the answer. added missing required key attribute. Commented Nov 18, 2021 at 9:53

You must log in to answer this question.

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