How to Retrieve AEM Component Property Value in JavaScript | Community
Skip to main content
November 25, 2023
Solved

How to Retrieve AEM Component Property Value in JavaScript

  • November 25, 2023
  • 2 replies
  • 3413 views

 

Hello AEM Community,

 

I'm facing a challenge with retrieving a component property value in JavaScript.

 

Specifically, I have a component named "userdetails" that includes a text field labeled "first name." The corresponding property for this field is stored as "fName." My objective is to access the value of this property ("fName") in JavaScript.

 

Could someone kindly assist me with the correct approach or code snippet to achieve this? Any guidance or insights from the community would be greatly appreciated.

 

Thank you in advance for your support.

 

@arunpatidar@rezwanur @aanchal-sikka @parthasarathy @_manoj_kumar_  @satheeskannak 

@saravanan_dharmaraj  @markusbullaadobe 

 

 

```

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Rezwanur

Hi @rishabh17, You can use the "data-" attribute of HTML to set the property value against a key in HTL and retrieve it in Javascript.

HTL:

<div id="example-id" data-fname="${properties.fName}">

 

Clientlib JS:

$(document).ready(function () {
const element = document.querySelector("#example-id");
let firstName = element.dataset.fname;
}


Hope it helps. 

2 replies

Rezwanur
RezwanurAccepted solution
Level 2
November 25, 2023

Hi @rishabh17, You can use the "data-" attribute of HTML to set the property value against a key in HTL and retrieve it in Javascript.

HTL:

<div id="example-id" data-fname="${properties.fName}">

 

Clientlib JS:

$(document).ready(function () {
const element = document.querySelector("#example-id");
let firstName = element.dataset.fname;
}


Hope it helps. 

vineel_k
Level 2
November 25, 2023

Hi @rishabh17  follow the below steps

As you mentioned below is the Component node structure



get the property value "fName" using JavaScript Use API

script.js :

 

 

"use scrict" use (function() { var fName = granite.resource.properties["fName"]; return { fName:fName }; });

 

 

 userdetails.html :

 

 

<div data-sly-use.model="script.js"> <h2> Name : <p1>${model.fName}</p1></h2> </div>

 

 


Dialog structure:

Content rendering on Page:

Thanks,
vineel_k.