2017-04-07 76 views
0
名單

我使用的是動態組件裝載顯示與組件列表當* ngFor:Angular2 - 獲取名稱使用動態組件裝載包裝爲顯示器件

<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 plnkrthis question,如果你希望所有的代碼的例子,但是對於這部分相關的代碼如下所示:

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 

任何人都可以解釋我要去哪裏錯了嗎?或者,如果您知道更好的方法來獲取名稱/ ID /正在移動的組件的任何內容,我很樂意聽到它。

回答

0

所以我想通了,但如果我遵循最佳實踐,將不勝感激任何反饋。

首先,我將一個componentName輸入添加到將由D.C.L顯示的組件中。像這樣:

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