11

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.

15

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);
                }
            }
        );
    }
})

**

  • Thanks mate, It works. I've come around getReference, but haven't googled use cases of it. – ytiq Nov 21 '16 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! – patryk Jun 9 '18 at 19:32

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.