2016-06-28 28 views
2

無法在特定索引處添加組件。例如在plunker鏈接下。 PlunkerAddRemoveComponents角度2:動態添加特定/第n個位置的組件

在這裏,我只能在第一次在特定索引處添加組件。

export class AddRemoveDynamic { 
    idx: number = 0; 

    constructor(private _dcl: DynamicComponentLoader, private _e: ElementRef) { } 

    add() { 
     this._dcl.loadIntoLocation(DynamicCmp, this._e, 'location').then((ref) => { 
      ref.instance._ref = ref; 
      ref.instance._idx = this.idx++; 
     }); 
    } 
} 

我的方案是:

  • 單擊Add按鈕組件的3倍。它會連續創建3行 。
  • 然後點擊第二行添加按鈕,它會創建另一行。
  • ,然後再次單擊同一個按鈕上,它會創建組件下一 行

這裏,是一個問題,我想在接下來的每一次添加按鈕行創建組件。

回答

1

DynamicComponentLoader已棄用。

我創建了使用ViewContainerRef.createComponent()一個例子,它允許添加這些應該被添加的元素的索引:

class DynamicCmp { 
    _ref: ComponentRef; 
    _idx: number; 
    constructor(private resolver: ComponentResolver, private location:ViewContainerRef) { } 
    remove() { 
    this._ref.dispose(); 
    } 
    add1() { 
    this.resolver.resolveComponent(DynamicCmp).then((factory:ComponentFactory<any>) => { 
     let ref = this.location.createComponent(factory, 0) 
     ref.instance._ref = ref; 
     ref.instance._idx = this._idx++; 
    }); 
    } 
} 

Plunker example

+0

它的工作現在。謝謝你的幫助:):):)。再次感謝Gunter Zochbauer。 – user2932411