我试图通过
动态创建一个Angular2组件我没有使用DynamicComponentLoader,因为它被弃用了ViewContainerRef
和ComponentResolver
,但我不认为解析器正在正确创建组件。它只是在最后附加它。
我做错了什么?
我创建了一个包含源代码的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 :(得分: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/