簡體   English   中英

如何將Angular2組件動態加載到div中

[英]How do I load an Angular2 Component dynamically into a div

我正在嘗試動態創建Angular2組件

  1. 給它一個位置
  2. 返回組件

我不使用DynamicComponentLoader,因為它已棄用,並已用於ViewContainerRefComponentResolver但我認為解析器無法正確創建組件。 它只是在末尾附加。

我究竟做錯了什么?

我用源代碼創建了一個plnkr: 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));

也許你應該用這個

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

代替

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

在這里看看http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM