[英]How do I load an Angular2 Component dynamically into a div
我正在尝试动态创建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));
也许你应该用这个
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.