Query.Add而不是动态组件装载器(loadintolocation)(Query.Add in

2019-09-29 03:49发布

我使用动态组件加载器,“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 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) })
});

Answer 1:

你需要一个参考ViewContainerRef其作为目标。 您可以注入像

constructor(private viewContainerRef:ViewContainerRef) {}

或得到它在使用视图的元件@ViewChild()

<div #target></div>
@ViewChild('target', {read: ViewContainerRef}) target;

ViewContainerRef.createComponent(> = 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()已过时(beta.17)

然后添加像部件

this.dcl.loadNextToLocation(SomeComponent, this.target).then((cmpRef) => {
  this.cmpRef = cmpRef;
});

又见https://stackoverflow.com/a/36325468/217408的Plunker



文章来源: Query.Add instead of Dynamic Component Loader (loadintolocation)