Angular 2 : Add components at specific/nth position dynamically

标签 angular angular2-components

无法在特定索引处添加组件。例如下面的 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 行 持续不断。
  • 然后点击第二行添加按钮,它将创建另一行。
  • 再次单击同一按钮,它将创建下一个组件 行

这里是问题所在,我想每次在“添加按钮行”旁边创建组件。

最佳答案

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

关于 Angular 2 : Add components at specific/nth position dynamically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38071141/

相关文章:

Angular 2 : dynamic selector property

Angular 5 模板驱动的十进制输入

Angular 4 httpclient xml 响应

angular - Angular2中多个组件之间的两种方式数据绑定(bind)?

angular - 将自定义表单控件连接到 Angular 2 中的父表单验证

子路由上路由器导出内的 Angular 组件不会填充可用空间

angular - 通过组件Angular 2中的选择器传递参数

Angular 4 webpack sass sourcemap 文件几乎是空的(使用 ExtractTextPlugin)

angular - 我怎样才能将我的 ionic cli 降级到以前的版本?

angular - 从 ActivatedRouteSnapshot 获取路线详情