1

I am writing an app for angular 2 with ES5.

I want to have a component with dynamically loaded view child, that will load existing components.

I saw examples in TypeScript but I am failing do that in ES5, and to inject ng.core.ViewChild in component constructor based on a ng.core.Directive and update the contents of the DOM element ( marked with that directive) with a dynamically loaded, existent, component.

I've tried with

queries:[
    formBody: ng.core.ViewChild('formBody')
]

...and I get a ElementRef, but would need a ViewContainerRef to update DOM contents with a dynamically loaded component.

I've tried :

queries:[
    formBody: ng.core.ViewChild(app.FormBodyDirective)
]

... but I get a "empty" object. __proto__ object

Component is loaded like this:

ngAfterViewInit: function() {
    var dialogComponentFactory = this.componentResolver.resolveComponentFactory(app.FormBody1_Component);
    this.formBody = this.formBody.createComponent(dialogComponentFactory);
},

I have tried to inject ng.core.ViewContainerRef into component constructor:

.Class({
      constructor: [ 
        ng.core.ViewContainerRef,
        function(viewContainer){
          this.formBody = viewContainer
      }],

but this of course injects a instance of ng.core.ViewContainerRef for my 'qform' element, and I get the dynamically loaded component at the end of the 'qform' element

Link to plunker with my code (not working) http://plnkr.co/edit/mRxGKYvKy8tHRjupNzju?p=preview

I would be very grateful if someone would help me sort this out, or throw a hint..

Thanks !

Svenv
  • 369
  • 1
  • 3
  • 14

1 Answers1

0

I finally find a solution. I am not sure that this is the best and most elegant way, but it works.

I injected ng.core.ViewContainerRef, in directive constructor and saved it's instance into class member.

The directive class member was accessible from within component. It was made available through component's queries option.

The directive:

app.FormBodyDirective = 
    ng.core.Directive({
      selector: '[formBody]'
    }).Class({
      constructor: [
        ng.core.ViewContainerRef,
        function(viewContainer){
          this._viewContainer = viewContainer;
      }]
    });

The component:

//...
queries : {
     formBody: new ng.core.ViewChild(app.FormBodyDirective)
},
directives:[ app.FormBodyDirective ]
//...

Working plunker: http://plnkr.co/edit/ooWhiMqSFDtGNGdW3LMK?p=preview

Svenv
  • 369
  • 1
  • 3
  • 14