Angular2 - 使用动态组件加载器包装器显示组件列表时获取名称

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

我正在使用动态组件加载器显示带有 *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>

类型为数组:types = [ TestAComponent, TestBComponent, TestCComponent];

在 dcl-wrapper 组件中,我已经能够访问组件的索引,但我不知道如何输出组件的名称。如果您需要所有代码,我使用 this plnkr from 作为示例,但是对于这部分的相关代码如下所示:

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

...

我得到:

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

谁能解释我哪里出错了?或者,如果您知道获取正在移动的组件的 name/id/whatever 的更好方法,我很想听听。

所以我明白了这一点,但如果我遵循最佳实践,我将不胜感激任何和所有反馈。

首先,我向 D.C.L 将要显示的组件添加了一个 componentName 输入。像这样:

@Input() componentName = 'whateverComponentNameHere';

然后向我的工厂添加一个额外的 属性 到每个实例,如下所示:

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();