Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 342
AlvYuste Avatar asked Nov 28 '25 14:11

AlvYuste


1 Answers

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

like image 114
Günter Zöchbauer Avatar answered Dec 01 '25 07:12

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!