0

I want to get the field types at a lightning component dynamically from js controller. I have the following code: Component

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

    <!--Define Attributes -->
    <aura:attribute name="page1" type="Boolean" default="true"/>
    <aura:attribute name="page2" type="Boolean" default="false"/>
    <aura:attribute name="numberOfFields" type="Integer[]" />
    <aura:attribute name="typeFields" type="String[]"/>
    <aura:attribute name="typeField1" type="String"/>
    <aura:attribute name="typeField1-2" type="String" />
    <aura:attribute name="typeField1-3" type="String" />

    <!--Main body -->
    {!v.typeField1}
    <aura:iteration items="{!v.numberOfFields}" var="item">

        <lightning:input type="{!v.typeFields[!item]}" name="{!item}" label="Enter a value" />
    </aura:iteration>

Controller

//Function on page Loading
    doInit: function(component, event, helper) {
        component.set("v.typeField1", "date");
        component.set("v.numberOfFields", [1,2,3,4,5,6,7,8]);
        component.set("v.typeFields", ["date", "text","date", "text","date", "text","date", "text",]);
        console.log('ola kala');
        console.log(component.get('v.typeField1'));
        console.log('Number of fields is: ' +component.get('v.numberOfFields'));
        console.log('Type of fields are: ' +component.get('v.typeFields'));                               
    },   

the problem is in the penultimate line of the component (html) code. I want to give the field type dynamically but i cannot have a nested attribute. What i actually try to achieve is to say: type="{!v.typeFields[0]}" type="{!v.typeFields[1]}" type="{!v.typeFields[2]}" .....and so on.... Any ideas ?

1 Answer 1

3

You can create one array of javaScript Object like below:-

    var fieldsArray = [
                { type: 'date', number: '1' },
                { type: 'text', number: '2' },
                { type: 'date', number: '3' },
            ]
    component.set("v.fields",fieldsArray);

and then you can iterate over it:-

<aura:attribute name="fields" type="Object[]" />
<aura:iteration items="{!v.fields}" var="item">
        <lightning:input type="{!item.type}" name="{!item.number}" label="Enter a value" />
 </aura:iteration>
1
  • Sanket, thans for your quick and awesome response :) Commented Mar 20, 2020 at 8:31

You must log in to answer this question.

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