AlvYuste
AlvYuste

Reputation: 945

Load a Component in custom element dynamically

I'm trying to inject a component on a container dinamically

Component:

@Component({...})
export class InvestmentProcess{

    @ViewChild('container') container;
    constructor(public dcl: DynamicComponentLoader) {}

    loadComponent(fooComponent: Type){
        this.dcl.loadNextToLocation(fooComponent, container);
    }
}

Template:

<div #container> </div>

When I run the function loadComponent the following error is thrown:

TypeError: location.createComponent is not a function

That's becouse container is an ElementRef typed variable, and loadNextToLocation expects a ViewContainerRef as the second parameter. As official docs said, the ViewContainerRef can be extracted from an element via @ViewChild, but I haven't find any example to do it properly.

Working with Angular2.0.0rc1

Upvotes: 3

Views: 1099

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657731

DynamicComponentLoader is going to be deprecated. Use ViewContainerRef.createComponent()

@Component({...})
export class InvestmentProcess{

    @ViewChild('container', {read: ViewContainerRef}) container:ViewContainerRef;
    constructor(private resolver: ComponentResolver) {}

    loadComponent(fooComponent: Type){
      this.resolver.resolveComponent(fooComponent).then((factory:ComponentFactory<any>) => {
        this.cmpRef = this.target.createComponent(factory)
      });        
    }
}

See also Angular 2 dynamic tabs with user-click chosen components

Upvotes: 3

Related Questions