5

Is there currently a way (Spring 19 Pre-Release) to get a unique identifier for a Lightning Web Component (LWC) instance? This would be the equivalent of component.getGlobalId() and component.getLocalId() in the previous model.

  • What's the purpose behind using the global ID? As far as I can tell, there's no direct access to these values now, but I think there's probably an alternative solution to the problem that was solved by using a global ID value. – sfdcfox Jan 22 at 17:42
8

There is no equivalent of globalId and localId in LWC.

If you want to uniquely identify an element your component render, you can add a data attribute. Live example

<template>
  <button data-id="red-pill" onclick={handleClick}>Red pill</button>
  <button data-id="blue-pill" onclick={handleClick}>Blue pill</button>
</templat>
import { LightningElement } from 'lwc';

export default class Test extends from LightningElement {
  handleClick(evt) {
    console.log(evt.target.getAttribute('data-id')); // "red-pill" or "blue-pill"
  }
}

Note: Keep in mind that the id attribute is transformed by LWC at runtime to enforce the shadow DOM scoping. The usage of the id in the template is not recommended in this in this case.

  • 1
    Is the idea of a globally unique id floating around? One place that global Ids are being used in my aura components are in a framework that creates fields - it ensures that field 'name' attributes are globally unique so that their corresponding label's 'for' attribute are matched up. I guess I could 'register' ids to components in some kind of register attached to window like developer.salesforce.com/docs/atlas.en-us.lightning.meta/…. – Dafydd Johns Jan 27 at 22:00
  • By specification, the id attributes in shadow DOM are scoped to the component shadow. As long as the <label> and the <for> tags are part of the same shadow tree (same LWC component), the generated id at runtime will match. Live example – pmdartus Jan 28 at 7:08
0

Equivalent to aura:id is now data-id.

You can achieve similar results as such:

<template>
  <lightning-record-edit-form data-id="userform"></lightning-record-edit-form>
</template>
this.template.querySelector('[data-id="userform"]').submit();
0

Just to add a little more color to this discussion, data attributes are one way to uniquely identify elements in your template, but you could just as well use classes. Before shadow DOM, it was a common practice to think up creative ways to construct unique IDs and classes (e.g., id="${section}-${componentName}-{$id}") to avoid collisions with other elements in the DOM, but shadow DOM semantics ensure that your styles don't leak and that your DOM queries only return elements in your template, etc, so using classes like .blue and .red should also work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.