2016-05-15 72 views
0

我試圖通過如何加載Angular2組件動態地爲一個div

  1. 即時創建一個Angular2組件給它一個位置
  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)); 
+0

查看我的例子http://stackoverflow.com/a/372​​32017/370935 –

+0

@Aredhel我看到了,但我深深地迷失了。我似乎無法弄清楚如何找到目標以及如何引導渲染器。 –

+0

渲染器分配在'app.component.ts','this.renderer = TwoRendererComponent'中,目標是'DclWrapperComponent'模板中的'#target'標籤,用於聲明'@ViewChild(...) target'。該組件在'updateComponent'中使用'target.createComponent'創建。 –

回答

0

也許你應該使用這個

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/