【问题标题】:Angular 2: Add components at specific/nth position dynamicallyAngular 2:在特定/第 n 个位置动态添加组件
【发布时间】:2016-06-28 08:38:22
【问题描述】:

无法在特定索引处添加组件。例如,在 plunker 链接下方。 PlunkerAddRemoveComponents

在这里,我只能在第一次在特定索引处添加组件。

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

我的场景是:

  • 单击“添加组件”按钮 3 次。它将创建 3 行 连续不断。
  • 然后单击第二行添加按钮,它将创建另一行。
  • 再次点击同一个按钮,它将创建下一个组件 行

问题来了,我想每次都在添加按钮行旁边创建组件。

【问题讨论】:

    标签: angular angular2-components


    【解决方案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

    【讨论】:

    • 现在可以使用了。谢谢你的帮助:):):)。再次感谢 Gunter Zochbauer。
    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 2023-03-30
    • 2017-05-18
    • 2017-07-17
    相关资源
    最近更新 更多