Component Composition in Lightning Aura Components

Component Composition in Lightning Aura Components let you build more efficient applications and components.

Component composition happens when you nest one or more components in another component. To build a component body, you can add components within the body. This component composition in Lightning Aura enables you to build complex components from simpler building-block components. The use of composition make code reuse and testing become easier

Consider the following components – firstChildCom.cmp and secondChildCom.cmp

<!--firstChildCom.cmp-->
<aura:component >
    <div>
 I'm the first child. Check out my style
</div>
</aura:component>

Below is the firstChildCom.css

.THIS {
color: green;
font-size: 120%;
}
The output of the firstChildCom markup is attached

Output of the first Child

Below is the secondChildCom.cmp

<aura:component >
	<aura:attribute name="secChild" type="String" default="second child"/>
<p class="sec">Here is the {!v.secChild}! </p>
</aura:component>

The secondChildCom.css

.THIS.sec {
     color: blue;
    font-size: 120%;
}

The output for the secondChildCom.cmp

Output for Second Child

Here is first2ndParentCom.cmp that uses composition to include other components in its markup

<aura:component >
 <div>Check out these firstChid and secondChild components within a component</div>
<c:firstChildCom/>
<c:secondChildCom secChild="component within component"/>	
</aura:component>

Note how first2ndParentCom.cmp references thefirstChild.cmp component, which lives in the c namespace using its descriptor c:firstChild. It also references c:secondChidCom setting the attribute values in a component as part of the component tag. first2ndParentCom.cmp sets the secChild attribute of secondChidCom.cmp to “component within componen

The output of first2ndParentCom.cmp

Output of first 2nd Parent

Passing of Attribute

It is possible to pass attributes to nested components just like the first2ndParentCom2.cmp that includes an extra passthrough attribute.
The default value of the first2ndParentCom2.cmp attribute is passed through as the attribute value for c:secondChildCom

<aura:component>
    
	<aura:attribute name="parentPassthru" type="String" default="passed through attribute"/>
    
    <div>Check out these firstChid and secondChild components within a component</div>
    <c:firstChildCom/>    
    <c:secondChildCom secChild="{#v.parentPassthru}"/>	

</aura:component>

Output

Output

The {#v.parentPassthru} unlike the {!v.parentPassthru} is an unbound expression which means that any change to the value of the secChild attribute in c:secondChildCom does not propagate back to affect the value of the parentPassthru attribute in c:first2ndParentCom2

Reference
Lightning Aura Components Developer Guide