Search code examples
angularangular7

Angular Bind Multiple Elements to One Object Returned from Function


I'm using Angular 7. I have a table that lists out buildings, where each building has several dollar values in it (such as Personal Property, Special Equipment, etc). In the table footer I would like to sum these values.

The component in charge has an input property that contains several groups of buildings, essentially an array of arrays of buildings, and I want to get the sums for each inner array.

Is it possible for this component to have a function that takes 1 group of buildings and returns an object, the properties of which are the various sums, and bind multiple DOM elements to that 1 function-generated object?

My hope is to avoid having to iterate through the buildings once for each sum, and to avoid storing the calculated value in the component. Something like the ability to "store" the object in a DOM element, similar to the let in an *ngFor? I only need it for 1 way binding.

Something like this (where ngVariable is made up):

<tfoot ngVariable="sumBuildings(group) as sums">
    <td>{{ sums.persProp }}</td>
    <td>{{ sums.specEquip }}</td>
</tfoot>

If there isn't such a thing, my next plan is to just build an inner component that handles a single group of buildings, and can calculate the totals on init, then I can just bind to that object. But ngVariable sounds easier.

Thanks!


Solution

  • Well, I don't know if this is an "appropriate" solution, but it definitely works. *ngIf does exactly what I'm looking for. I was able to write:

    <tfoot *ngIf="sumBuildings(group) as sums">
        <td>{{ sums.persProp }}</td>
        <td>{{ sums.specEquip }}</td>
    </tfoot>
    

    And I was able to bind to sums. It feels dirty since I'm using a side effect, but it does what I need.