Dynamically rendering a component via a template helper


#1

I am currently trying to render a component in a helper dynamically based on a passed in value (for simplicity I have hardcoded the value as my-foo in the examples)

I have used the following code in my helper to attempt to achieve this

function renderComponent(componentName, options) {  
    var helper = Ember.Handlebars.resolveHelper(options.data.view.container, componentName);
    return helper.call(this, options);
}

export {
  renderComponent
};

export default Ember.Handlebars.makeBoundHelper(renderComponent);

From the following post http://discuss.emberjs.com/t/how-to-dynamically-load-ember-components-by-name-in-a-template/6312

It is being invoked from a view via…

var Widget = Ember.View.extend({
   tagName: 'li',
   template: Ember.Handlebars.compile('{{render-component "my-foo"}}')
});

export default Widget;

I seem to get the following error…

Uncaught TypeError: Cannot read property ‘pushChildView’ of nullvendor.js:54334 merge.appendChildvendor.js:56121 CoreView.extend.appendChildvendor.js:22824 EmberObject.create.helpervendor.js:23051 viewHelpervendor.js:17971 EmberHandlebars.makeViewHelperdashboard/helpers/render-component.js:11 renderComponentvendor.js:20460 bindView.normalizedValuevendor.js:23412 SimpleHandlebarsView.rendervendor.js:52700 EmberRenderer_createElementvendor.js:23802 Renderer_renderTreevendor.js:23879 (anonymous function)vendor.js:13853 DeferredActionQueues.invokevendor.js:13923 DeferredActionQueues.flushvendor.js:13309 Backburner.endvendor.js:13364 Backburner.runvendor.js:13729 executeTimersvendor.js:13718 (anonymous function)

If I hard code the component name it seems to work

Ember.Handlebars.compile('{{my-foo}}')

I am using ember 1.8.1 and ember-cli 0.1.3. I am pretty new to Ember so any help would be greatly appreciated.

Thanks in advance


#2

I’ve written an addon which should help you - https://github.com/minutebase/ember-dynamic-component


#3

Thanks that is very useful I will check it out. Any idea why this error actually occurs?

I am interested in why my initial approach failed?

Thanks for your time.


#4

This is now integrated into Ember core http://emberjs.com/blog/2015/02/07/ember-1-10-0-released.html#toc_component-helper