0

I'm using the DynamicComponentLoader to load a component dynamically, which is passed by a parameter. I'd like to use the old loadIntoLocation method, but that has been removed as of beta16 (I'm using RC0).

In the end I would like to be able to load a component inside the #activeComponent div while still being able to toggle a parents visibility, like so:

<div *ngIf="isOpen>
  <div #activeComponent></div>
</div>

This is what I got:

@Input() activeComponent: any;
constructor(){}
ngOnChanges() {
  this._dynamicComponentLoader.loadNextToLocation(this.activeComponent, this._viewContainerRef);
}

And this works, but, as the method's name implies, the component is loaded next to location, as a sibling. I would like a child, like the old loadIntoLocation method.

The Angular 2 beta16 changelog writes: Use @ViewChild(‘myVar’, read: ViewContainerRef) to get hold of a ViewContainerRef at an element with variable myVar. Then call DynamicComponentLoader.loadNextToLocation.

This is what I would like to work:

@ViewChild('activeComponent',) child: ViewContainerRef;
constructor(){}
ngOnChanges() {
    if (!this.activeComponent) return;
    this._dynamicComponentLoader.loadNextToLocation(this.activeComponent, this.child);

}

But I'm getting : TypeError: location.createComponent is not a function.

Anyone who got the _dynamicComponentLoader with @ViewChild working?

RobSeg
  • 985
  • 4
  • 14
  • 37

1 Answers1

4

Similar question here: Adding new Component element to DOM in Angular 2 at runtime doesn't render the component

And here's the link for the plunker: Plunker

 @Component({
      selector: 'my-app',
      template: `<button (click)="addCmp()" #activeComponent>add</button>
      <hero-list></hero-list>
      <sales-tax></sales-tax>
      `,
      directives: [HeroListComponent, SalesTaxComponent]
    })
    export class AppComponent {
      @ViewChild('activeComponent',{read: ViewContainerRef}) activeComponent: ViewContainerRef;

      constructor(private dcl: DynamicComponentLoader, injector: Injector,private resolver: ComponentResolver) {}

      addCmp(){
        console.log('adding');
        //change HeroListComponent with the one you want
        this.resolver.resolveComponent(HeroListComponent).then((factory:ComponentFactory<any>) => {
              this.cmpRef = this.activeComponent.createComponent(factory)
            });
          }
Community
  • 1
  • 1
eko
  • 39,722
  • 10
  • 72
  • 98