2016-06-28 40 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