关于typescript:使用Query.Add代替动态组件加载程序(loadintolocation)

Query.Add instead of Dynamic Component Loader (loadintolocation)

我正在使用动态组件加载程序,即" loadIntoLocation"变体。但这在Angular2的最新版本中不再可用。

如何转换此代码并获得相同的功能?

1
2
3
4
5
6
7
8
    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。

最终解决方案

1
2
3
4
5
6
7
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) })
});


您需要引用用作目标的ViewContainerRef。您可以像

一样注入

1
constructor(private viewContainerRef:ViewContainerRef) {}

或使用@ViewChild()

获取视图中的元素

1
 
1
@ViewChild('target', {read: ViewContainerRef}) target;

ViewContainerRef.createComponent(> = beta.17)

注入ComponentResolver

1
2
3
constructor(private resolver: ComponentResolver,
    /* if required also
    private viewContainerRef:ViewContainerRef */) {}

然后添加类似

的组件

1
2
3
4
5
6
7
8
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory) => {
  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()(第17版)

然后添加类似

的组件

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

另请参阅https://stackoverflow.com/a/36325468/217408