0

I'm trying to create an Angular2 Component on the fly by

  1. Giving it a location
  2. Returning the component

I'm not using DynamicComponentLoader because it's deprecated and went for the ViewContainerRef and the ComponentResolver but I don't think the resolver is creating the component properly. It's only appending it at the end.

What am I doing wrong?

I've created a plnkr with the source code: http://plnkr.co/edit/a2esZiVpiV5f1r4uEufX?p=preview

@Component({
  selector : 'marker-component',
  template : '<strong>OH BABY ITS WORKING</strong>'
})
class MarkerComponent {

}

@Component({
  selector: 'my-app',
  template : `
    <div id="map"></div>
  `
})
export class App implements NgOnInit {

  map: any

  constructor(
    private compiler: ComponentResolver, 
    private viewContainer: ViewContainerRef) {

  }

  ngOnInit() {
    this.map = L.mapbox.map('map', 'mapbox.streets').setView([40, -74.50], 9);
    var cssIcon = L.divIcon({
      // Specify a class name we can refer to in CSS.
      className: 'css-icon',
      html: `<marker-component></marker-component>`,
      iconSize: [60, 60]
    });
    L.marker([40, -74.50], {icon: cssIcon}).addTo(this.map);

    this.compiler.resolveComponent(MarkerComponent).then((factory) => 
        this.viewContainer.createComponent(factory, 0, this.viewContainer.injector)); 
  }
}

bootstrap(App, [...HTTP_PROVIDERS]).catch(err => console.error(err));
Max Alexander
  • 5,471
  • 6
  • 38
  • 52
  • Check my example here http://stackoverflow.com/a/37232017/370935 – Thorsten Westheider May 15 '16 at 03:46
  • @Aredhel I saw but I'm deeply lost. I can't seem to figure out what it takes to find the target and how to bootstrap the renderer. – Max Alexander May 15 '16 at 03:51
  • The renderer is assigned in `app.component.ts`, `this.renderer = TwoRendererComponent`, the target is the label `#target` in `DclWrapperComponent`s template and used to declare the `@ViewChild(...) target`. The component is created in `updateComponent` using `target.createComponent`. – Thorsten Westheider May 15 '16 at 03:57
  • Ah I see but what if the target is created asynchronously outside of the Angular2 scope? How can you hold on to a ViewChild of the target? – Max Alexander May 15 '16 at 04:04

1 Answers1

0

maybe you should use this

    const injector = ReflectiveInjector.fromResolvedProviders([], this._viewContainer.parentInjector);
this._currentComponentRef = this._viewContainer.createComponent(factory, 0, injector, []);

instead of

this.viewContainer.createComponent(factory, 0, this.viewContainer.injector));

take a look here http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2/

Roman Gural
  • 116
  • 4