Expand my Community achievements bar.

July 31st AEM Gems Webinar: Elevate your AEM development to master the integration of private GitHub repositories within AEM Cloud Manager.
SOLVED

How to Retrieve AEM Component Property Value in JavaScript

Avatar

Level 1

 

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  @markus_bulla_adobe 

 

 

```

1 Accepted Solution

Avatar

Correct answer by
Level 2

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. 

View solution in original post

2 Replies

Avatar

Correct answer by
Level 2

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. 

Avatar

Level 2

Hi @Rishabh17  follow the below steps

As you mentioned below is the Component node structure

Screenshot 2023-11-26 at 12.12.01 AM.png

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:

Screenshot 2023-11-26 at 12.18.56 AM.png

Content rendering on Page:

Screenshot 2023-11-26 at 12.19.32 AM.png

Thanks,
vineel_k.