像javascript的insertBefore函数一样插入一个组件

时间:2017-08-26 11:14:58

标签: angular

我想在这些模式中插入动态创建的组件:

Starting case: 
<div id="X">
</div>

在div中插入一个id为X的新组件,产生这个..

<div id="X">
<new-component></new-component>
</div>

然后,在按钮单击/或任何事件(异步等...)后,我想在第一个插入的组件之前插入一个新组件。

<div id="X">
<new-component></new-component> // the new component inserted 
<new-component></new-component> //the first inserted component
</div>

反之亦然,我想再次在给定的参考节点之后插入一个组件,就像javascript的插入节点一样。

我在想的是获取组件的元素并通过js手动调整它。是否有更好的方法来执行这些功能而不会导致这种情况?谢谢。顺便说一句,我正在使用角4。

1 个答案:

答案 0 :(得分:2)

我希望你能实现这样的目标:

父HTML:

<button type="button" (click)=add()>Add</button>
 <div *ngFor="let child of children; let i = index">
    <child [childId]="child.id.toString()"></child> 
 </div>

家长班:

  children = [];
  add() {
    //add at the start
    this.children.unshift({id:this.children.length+1});
  }

儿童HTML

  <input type="text" [value]="'I am child number'+ childId">

儿童班:

export class ChildComponent {
  // to keep the track of the child
  @Input('childId') private childId;
}

所以你不必直接操纵DOM。

Plunker