我正在使用动态组件加载器,即“loadIntoLocation”变体。但是在最新版本的Angular2中已不再可用。
如何转换此代码并获得相同的功能?
this.dcl.loadIntoLocation(OpsComponent, this._el , "dynamicpanel").then((cmp)=>{
this.compRef = cmp
// input
cmp.instance.forwarddata = { name: "teddy" }
// output
cmp.instance.emitter.subscribe(event=>{ console.log(event) })
return cmp
})
如何重构,保留功能并使用新的Query.read?
违规变更通知:
核心:添加Query.read并删除DynamicComponentLoader.loadIntoLocation。 (efbd446)
DynamicComponentLoader.loadIntoLocation has been removed. Use
@ ViewChild('myVar',读取:ViewContainerRef)to get hold of a
ViewContainerRef at an element with variable
myVar`。
已删除DynamicComponentLoader.loadIntoLocation。使用@ViewChild('myVar',读取:ViewContainerRef)来获取具有变量myVar的元素的ViewContainerRef。然后调用DynamicComponentLoader.loadNextToLocation。 DynamicComponentLoader.loadNextToLocation现在采用ViewContainerRef而不是ElementRef。
最终解决方案
this.resolver.resolveComponent(ChildComponent).then((factory:ComponentFactory) => {
this.compRef = this.dynamicpanel.createComponent(factory)
// input
this.compRef.instance.forwarddata = { name: "Teddy"}
// output
this.compRef.instance.emitter.subscribe(event => { this.onChildEvent(event) })
});
答案 0 :(得分:1)
您需要引用ViewContainerRef
作为目标。您可以像
constructor(private viewContainerRef:ViewContainerRef) {}
或使用@ViewChild()
<div #target></div>
@ViewChild('target', {read: ViewContainerRef}) target;
ViewContainerRef.createComponent(&gt; = beta.17)
注入ComponentResolver
constructor(private resolver: ComponentResolver,
/* if required also
private viewContainerRef:ViewContainerRef */) {}
然后添加像
这样的组件this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory);
// here you can set inputs and set up subscriptions to outputs
// input
this.cmpRef.instance.someInput = someValue;
// output
this.cmpRef.instance.someOutput.subscribe(event=>{ console.log(event) });
});
不推荐使用DynamicComponentLoader.loadNextToLocation()(测试版)
然后添加像
这样的组件this.dcl.loadNextToLocation(SomeComponent, this.target).then((cmpRef) => {
this.cmpRef = cmpRef;
});
另请参阅https://stackoverflow.com/a/36325468/217408了解Plunker