1

I am using Dynamic Component Loader, the "loadIntoLocation" variant. But this is no longer available in latest versions of Angular2.

How to transform this code and get same functionality?

    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
    })

How to refactor this, keep functionality and use new Query.read instead?

Breaking change notice:

core: add Query.read and remove DynamicComponentLoader.loadIntoLocation. (efbd446)

DynamicComponentLoader.loadIntoLocationhas been removed. Use@ViewChild(‘myVar’, read: ViewContainerRef)to get hold of aViewContainerRefat an element with variablemyVar`.

DynamicComponentLoader.loadIntoLocation has been removed. Use @ViewChild(‘myVar’, read: ViewContainerRef) to get hold of a ViewContainerRef at an element with variable myVar. Then call DynamicComponentLoader.loadNextToLocation. DynamicComponentLoader.loadNextToLocation now takes a ViewContainerRef instead of an ElementRef.

FINAL SOLUTION

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) })
});
Teddy
  • 2,277
  • 3
  • 15
  • 19

1 Answers1

1

You need a reference to ViewContainerRef which is used as target. You can either inject it like

constructor(private viewContainerRef:ViewContainerRef) {}

or get it for an element in the view using @ViewChild()

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

ViewContainerRef.createComponent (>= beta.17)

Inject the ComponentResolver

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

then add the component like

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() deprecated (beta.17)

then add the component like

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

See also https://stackoverflow.com/a/36325468/217408 for a Plunker

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567