Nested components and angle brackets, a sneaky solution

UPDATE With the release of 3.10 you can now use :: for nesting. See bottom of the post.

If you have been following Ember development, you might have noticed that starting with Ember v3.4, you have a new way to invoke components in your templates called angle bracket syntax.

In the new syntax, instead of invoking a component like so:

{{user-profile user=user}}

You can invoke it as:

<UserProfile @user={{user}} />

The angle bracket syntax has the advantage of differentiating arguments to the component, @user, from HTML attributes. To set the class using this syntax, you would do:

<UserProfile @user={{user}} class='profile' />

This presents a problem if you have components nested inside a folder in your project, as angle bracket syntax does not support slashes (/) in the component name. Using the recently introduced let helper and the trusted component helper, however, we can do a sneaky combo and go around this limitation.

Let’s say you have a component at ui/x-button, and you want to use it.
You do the following:

{{#let (component 'ui/x-button') as |XButton|}}
  <XButton>Click me</XButton>
{{/let}}

And… That’s it!

Hope this comes in handy for one of y'all.

Actually, one more thing. Don’t forget that you can pass multiple arguments to let! You forgot to wrap ui/x-button with a ui/x-form component, let’s fix that:

{{#let (component 'ui/x-form') (component 'ui/x-button') as |XForm XButton|}}
  <XForm>
    <XButton>Click me</XButton>
  </XForm>
{{/let}}

Ember 3.10 onwards #

As mentioned in the update, with the release of Ember 3.10 came template syntax for nested folders.

You can now easily write the two nested components mentioned above as follows:

<UI::XForm>
  <UI::XButton>Click me</UI::XButton>
</UI::XForm>
 
69
Kudos
 
69
Kudos

Now read this

To `attrs` or not to `attrs`

The advice to avoid attrs is still relevant as of Ember 2.12, and until angle bracket components are released in Ember. In this post I will attempt to explain why you should avoid using attrs in your Ember.js application code. tl;dr... Continue →