Reputation: 900
I want to insert a dynamically created component in these modes:
Starting case:
<div id="X">
</div>
Insert a new component inside the div with a id of X, resulting to this..
<div id="X">
<new-component></new-component>
</div>
and then, after a button click/or any event (async etc...) I want to insert an new component before the first inserted component.
<div id="X">
<new-component></new-component> // the new component inserted
<new-component></new-component> //the first inserted component
</div>
and vice versa, I want to insert a component after a given reference node again just like javascript's insert node.
What I'm thinking of is to get the component's element and adjusting it manually via js. Is there a better way to perform these functions without resulting to that? Thanks. I'm using angular 4 by the way.
Upvotes: 1
Views: 488
Reputation: 28708
I hope you are looking to realise something like this:
Parent HTML:
<button type="button" (click)=add()>Add</button>
<div *ngFor="let child of children; let i = index">
<child [childId]="child.id.toString()"></child>
</div>
Parent Class:
children = [];
add() {
//add at the start
this.children.unshift({id:this.children.length+1});
}
Child HTML
<input type="text" [value]="'I am child number'+ childId">
Child class:
export class ChildComponent {
// to keep the track of the child
@Input('childId') private childId;
}
So you don't have to manipulate the DOM directly.
Upvotes: 2