Aurelia makes it trivial to de-compose your web application into individual components, each with a single responsibility. There are two methods of decomposing applications with Aurelia. Custom Elements and Dynamic composition. I’ll use the contacts app example from the Aurelia GitHub Organisation to demonstrate how to put both of these techniques into action.
Dynamic Composition
Let’s start with Dynamic composition, as it requires the least code change to implement.
The contact-detail.html page is used to view and modify the details of a given contact:
The following code snippet is used to define the profile header section:
We can use dynamic composition to pull this out into a separate file and slim down the contact profile page. The first step to do this is to create a new template file and extract the profile header code into it:
touch profile-header.html
The next step is to dynamically compose this into our contact-detail page:
The resulting HTML is almost correct, but there is one more thing we need to modify first.
As you can see in the screenshots, the Bootstrap styling is not quite right. An inspection via the Chrome Dev Tools shows the cause. The HTML has been embedded within the template container:
We can fix this by adding the containerless attribute to our compose:
Now we should have the same profile displayed as we did to start with:
Custom Elements
If we want more control in the module that we are composing into the page we could instead use a custom element. To do this, the first step is to create a corresponding profile-header.js file to pair with our profile-header.html file.
touch profile-header.js
We’ve got one additional change here. We are going to pass the firstname property of the contact from the parent view-model through to the child view model so that we can include it as a part of the profile header.
The last step is to modify contact-detail.html template to use the custom element:
And modify the profile-header.html template to make use of the firstname property:
The first name is now included as a part of the profile header.
This is a trivial example, but demonstrates the simplicity with which we can break down Aurelia applications into composable views.
Leave a Reply