0

I have an apex controller which returns a list to my javascript controller.
Within clinet side javascript, i want to iterate through list of the object and create one string which will contain anchor tags also. I used component.set("v.myString",customLongString) so that it can be viewed in lightning.

The javascript string is something like this :

An apple a day keeps the doctor away for <a href="javascript void(0); onClick="handleSomething();">#12344</a> times.

When the above string is rendered in lightning, it still displaying the HTML tags instead of making it as a hyperlink. Any idea what i can do for it ?. The string can contain multiple or 4 hyperlinks and many more text.

1 Answer 1

2

Whenever you are using

component.set("v.myString",customLongString);

it will literally print whats there in the variable customLongString. It will assume it to be a string and will not parse the string. Hence the HTML was displaying in the UI.

As a work around look at the below code

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

<!-- If your String is static. Try String Interpolation-->
<p>This is from static</p>
hello <a onclick="{!c.sayHello}" name="{!v.testList[1].strValue}">{!v.testList[1].strValue}</a> Chander

<!-- If your Stirng is dynamic - Build the list similar to the one in doInit method and loop through -->
<p>This is from dynamic</p>
<aura:iteration items="{!v.testList}" var="item">
    <aura:if isTrue="{!item.isOnclickEnabled}">             
        <a href="javascript:void(0)" onclick="{!c.sayHello}" name="{!item.strValue}">{!item.strValue}</a>&nbsp;
        <aura:set attribute="else">
            <span>{!item.strValue} &nbsp;</span>
        </aura:set>
    </aura:if>                  
</aura:iteration>    

In the controller build your dynamic testList and generate a string of your requirement. Onclick you will know which string you clicked and process it in the controller

({
    sayHello : function(cmp, event, helper) {
        var stringClicked = event.srcElement.name;
        alert(stringClicked);
    },

    doInit : function(cmp, event, helper){
        var testList = [
            {strValue : 'hello', isOnclickEnabled : false},
            {strValue : 'Mohan', isOnclickEnabled : true},
            {strValue : 'Chander', isOnclickEnabled : false}
        ];
        cmp.set("v.testList", testList);
    }
})

UI inth

1
  • Got it. This is exactly what i am doing as an alternative
    – Darkdog
    Commented Sep 4, 2019 at 19:17

You must log in to answer this question.

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