12

I'm trying out to generate input elements dynamically and wasn't able to bind value attribute.

I getting following error when trying to display component:

enter image description here

testDynamicBinding.cmp

<aura:component description="testDynamicBinding">
    <aura:attribute name="testAttr" type="String" default="Hello World"/>

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

    {!v.body}

</aura:component>

testDynamicBindingController.js

({
    doInit: function(cmp){
        $A.createComponent(
            'ui:outputText',
            {
                value: '{!v.testAttr}'
            },
            function(element, status, errorMessage){
                if (cmp.isValid() && status == 'SUCCESS'){
                    var body = cmp.get('v.body');

                    body.push(element);

                    cmp.set('v.body', element);
                }

            }
        );
    }
})

I don't understand why it gives me this error.

I tried following code (I think it's equivalent to what I try to generate) and that works fine.

<aura:component description="testDynamicBinding">
    <aura:attribute name="testAttr" type="String" default="Hello World"/>

    <aura:set attribute="body">
        <ui:outputText value="{!v.testAttr}"/>
    </aura:set>

</aura:component>

Any piece of advice would be appreciated.

Thanks a lot in advance.

1 Answer 1

17

1.In controller u need to get attribute reference value using cmp.getReference("v.testAttr")

2.And set the value to ui:output text

**

({
    doInit: function(cmp){
        var test = cmp.getReference("v.testAttr");
        $A.createComponent(
             'ui:outputText',
            {
                value: test
            },
            function(element, status, errorMessage){
                if (cmp.isValid() && status == 'SUCCESS'){
                    var body = cmp.get('v.body');
                    body.push(element);
                    cmp.set('v.body', element);
                }
            }
        );
    }
})

**

2
  • Thanks mate, It works. I've come around getReference, but haven't googled use cases of it. Commented Nov 21, 2016 at 11:20
  • Guys, just to confirm, cmp.getReference allows me to set 2-way data binding when I create components dynamically using $A.createComponent?? If Yes, this is simply GREAT! Commented Jun 9, 2018 at 19:32

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.