Search code examples
angularfactoryng2-dragula

Angular2 - Get Name When Using Dynamic Component Loader Wrapper To Display List of Components


I'm using a Dynamic Component Loader to display a list of components with a *ngFor:

<div [dragula]='"bag-one"' [dragulaModel]='types'>
  <div *ngFor="let component of types; let i = index">
    <dcl-wrapper [type]="component" [index]="i"></dcl-wrapper>
  </div>
</div>

With types being an array: types = [ TestAComponent, TestBComponent, TestCComponent];

Within the dcl-wrapper component I have been able to access the index of the components but I cannot figure out how to output the name of the components. I used this plnkr from this question as an example if you want all the code, but for the relevant code for this part looks like this:

export class DclWrapperComponent {

  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  @Input()
    set name(component: string){
      this.name = component;
    }
  @Input() 
    set index(i: number){
      this._index = i;
      console.log("Item index changed: ", this._index, this.name);
    }

...

and I get:

Item index changed:  0 undefined
Item index changed:  1 undefined
Item index changed:  2 undefined

Could anyone explain where I'm going wrong? Or if you know of a better way to get the name/id/whatever of the component that is being moved I would love to hear it.


Solution

  • So I figured this out but would appreciate any and all feedback if I'm following best practices.

    First I added a componentName Input to the components that are going to be displayed by the D.C.L. like this:

    @Input() componentName = 'whateverComponentNameHere';
    

    And then added to my factory an additional property to each instance like this:

    let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
    this.cmpRef = this.target.createComponent(factory)
    
    console.log(this.cmpRef.instance.componentName + ": " + this._index);
    ^^^Can access like this.
    
    this.cdRef.detectChanges();