Search code examples
angularangular2-components

Angular 2: Add components at specific/nth position dynamically


Unable to add components at specific index. Below the plunker link for example. PlunkerAddRemoveComponents

Here, I am able to add components at a specific index at the first time only.

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

My Scenario is:

  • Click on Add Component button 3 times. It will create 3 rows continuously.
  • Then click on second row Add button, it will create another row.
  • And again click on the same button, it will create component next one row

Here, is the problem, I want to create component at every time next to Add button row.


Solution

  • DynamicComponentLoader is deprecated.

    I created an example that uses ViewContainerRef.createComponent() that allows to add an index where the element should be added:

    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