2

I have an image tag :

<img src="{!v.ticketDetails.url}"  alt="Image not found" onerror="this.style.display='none'"/>

If image is not found, it shows broken Image icon on chrome. However this works with plain HTML but not working in lightning component.

HTML Code:

<html>
    <head>
    </head>
    <body>
        <img src="images.jpeg" onerror=" this.style.display='none'">
    </body>
</html>

How can I achieve same functionality in lightning component?

0
2

This is working for me. In lightning world, you cannot use inline javascript instead everything has to be handled by controller functions.

HelloWorldApp.app:

<aura:application extends="force:slds">
    <img src="images.jpeg" onerror="{!c.imageError}"></img>
</aura:application>

HelloWorldAppController.js::

({
    imageError: function(component,event,helper){
         event.target.style.display = 'none';
    }   
})
0
1

Direct DOM manipulation(especially on the DOM the framework manages) inside the controller is not recommended.

Though you can use the $A.util.addClass(),$A.util.removeClass() to achieve the same.

Quote from the doc:

You can modify CSS classes for a component outside a renderer by using the $A.util.addClass(), $A.util.removeClass(), and $A.util.toggleClass() methods.

Eg:

component:

<aura:component>
   <ui:button label="Toggle" press="{!c.toggle}"/>
   <p aura:id="text">Now you see me</p>
</aura:component>

controller:

({
    toggle : function(component, event, helper) {
       var toggleText = component.find("text");
       $A.util.toggleClass(toggleText, "toggle");
    }
})

css:

.THIS.toggle {
    display: none;
}

Please refer the section on Modifying the DOM in the LC dev guide.

0

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.