Dynamic field binding in Lightning (e.g. lightning:input)

This is to me the most restricting drawback of Lightning compared to Visualforce. A way to dynamically bind/access properties like values of fields.

To make complex component structures fast I don’t want to pass around queried SObjects. Instead I want to pass record Ids and field names. Lightning Data Service then fetches the record.

Saving this component:

<aura:component>
    <aura:attribute name="recordId" type="String" />
    <aura:attribute name="field" type="String" />
    <aura:attribute name="record" type="Object" access="private" />

    <force:recordData recordId="{!v.recordId}" targetFields="{!v.record}" layoutType="FULL" recordUpdated="{!c.init}" />

    <lightning:input value="{!v.record[field]}" ... />
</aura:component>

fails with:

Failed to save xyz.cmp: expecting a positive integer, found ‘field’ at
column 10 of expression: v.record[field]: Source

I know that this currently is as designed and I’m not interested in “dirty” quickhacks. I want to know:

  • Is there any IdeaExchange I could vote for?
  • Is this on anyones roadmap?
  • What’s the technical reason / design decision for not having this?

Answer

We understand that the ergonomics from a declarative point of view are great, but unfortunately there are big performance penalties and a bunch of quirks and functional issues supporting dynamic evaluation of expressions (ex. what would happen if you were to mutate the binding (bidirectional) in the children? – it will be very hard to mutate the object back given the dynamic expression).

Moreover, this approach will only solve very simple use cases, if you want to do any transformation or filtering, you will have to jump anyway to imperative code.

Here is a trivial workaround to achieve the same result:

({
  init: function (cmp) {
    var fields = Object.keys(cmp.get('v.record'));
    var filteredFields = fields.filter(function (f) { ... }) 
    cmp.set('v.filteredFields', filteredFields);
  }
})

Because of all of what I stated previously, I don’t think this feature will be likely to be prioritized, at least not until we refactor the internals of how the expressions work.

Attribution
Source : Link , Question Author : Robert Sösemann , Answer Author : Diego

Leave a Comment