I am trying to get some data from Apex controller and then change the styling of icons once component is rendered.
Here is the sample code:
HelloWorldApp.app
<aura:application extends="force:slds" controller="HelloWorldApexController">
<aura:attribute name="accList" type="Account[]"></aura:attribute>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<table aura:id="table-aura-id">
<thead>
<tr>
<th>Col Label</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.accList}" var="accVar">
<tr>
<td>
<lightning:buttonIcon iconName="utility:comments"
size="medium"
name="secondIcon"
aura:id="iconInsideTable"
alternativeText="Hello"
iconClass=""/>
</td>
</tr>
</aura:iteration>
</tbody>
</table>
</aura:application>
HelloWorldAppController.js:
({
doInit : function(component,event,helper){
var action = component.get("c.getAccounts");
action.setParams({
});
action.setCallback(this, function(actionResult) {
console.log('Server call inside doInit finished');
component.set("v.accList",actionResult.getReturnValue());
});
$A.enqueueAction(action);
}
})
HelloWorldApp.css:
.THIS .bgred{
background-color:rgb(0,191,255);
}
HelloWorldAppRenderer.js:
({
afterRender: function(component,helper){
this.superAfterRender();
console.log('afterRender event handler is running now');
var iconCmpList = component.find('iconInsideTable')
iconCmpList.forEach((iconCmp) => {
iconCmp.set("v.iconClass","bgred");
});
}
})
HelloWorldApexController.cls:
public class HelloWorldApexController {
@AuraEnabled
public static List<Account> getAccounts() {
return [SELECT Id,Name FROM Account LIMIT 2];
}
}
This is the error I am getting:
afterRender
event handler is running before the doInit
method is finished and it is not finding elements. Here is the browser console log:
What do I do to fix this? I want to change css of the elements(conditionally in js due to complex calculations) once the dom is constructed.
rerender()
override in my case. None of the other lifecycle events had the child components. But in my case, I only need to access the child record after some user interaction happens.