javascriptangularjsreactjscomponentsangularjs-ng-transclude

How can I achieve component composition in AngularJS (similar to React render props pattern)?


I am trying to create a grid component in AngularJS that has it's grid items provided at runtime. (think render props pattern in React).

I am trying to build this using the "new" AngularJS components API along with transclusion.

<grid-items>
   <grid-item-type-1></grid-item-type-1>
</grid-items>


<grid-items>
   <grid-item-type-2></grid-item-type-2>
</grid-items>

Any of these should be valid. <grid-items> should take care of the data and the <grod-item-type-x> should take care of how each individual item is going to be dislpayed.


Solution

  • After researching I have found out two ways to do this. One of them is to require the parent controller in the child component and use it's data, or by using the link function along with compile (this doesn't work using the components API), something like this:

    link: function(scope, element) {
          scope.items.forEach((item) => {
            const tpl = "<" + item.type + " item=" + item + " ></grid-item>"
            const child = $compile(tpl)(item)
            element.append(child);
          });
        }
    

    The above approach doesn't use transclusion but you can still use whatever child component is provided to the parent at runtime.