How to supply component and its parameters dynamically in a template

I have a parent component and a child component which extends the parent. I would like to add kind of polymorphic behaviour to the parent template. Basically I would like to instantiate a component inside the parent template which gets provided by the child along with its parameters. Somewhere in the parent template I have a construct like this (doesn’t work exactly as I want it though):

{{component this.formComponent …this.formArgs}}

The desired component gets properly created but it is not fed with the supplied arguments.

How can I supply parameters (the child supplies both - what to create and what args to pass) to the dynamically created component?

In general, I agree it is better to rely on composition vs inheritance but I would like to achieve this behaviour by inheritance.

Thanks!

I agree it is better to rely on composition vs inheritance but I would like to achieve this behaviour by inheritance.

not only that, but spreadable arguments lead to refactoring problems down the road, as it’s hard to tell what is actually used. Thankfully, in ember, changes to arguments that you don’t end up using don’t cause the component to re-render anything – so that’s a big plus to other ecosystems.

However,

…this.formArgs}}

This syntax is not possible at the moment, see this list of all the missing syntax / keywords I think we should add:

For solving your problem at hand tho, there are a couple less ergonomic ways.

Noticing

this.formComponent

I worry that this a string – you’ll want to make sure it’s a real component value, so you can make the transition to vite easier as we’re about to release an alpha of the embroider-vite stuff.

Here is a mini tutorial on dynamically chosen components:

Glimmer Tutorial

It’s worth noting that when when doing this type of component invocation, it’ll be easiest if all the components that you’re using have either the same args, or the same few shapes of args so that you can wrap each invocation style in an if statement.

For example:

{{#if isSelect}}
  use args for selects, specifically
{{else}}
  use args for everything else
{{/if}}

Hope this helps!

1 Like

Thanks for the information! At this point I guess it would be better if I refactor the code and rely on composition instead of inheritance/polymorphism. It’s more work but given the state of things right now it would be safer to go this way.

1 Like