3

I'm rendering dynamically created components from a component array with *ngFor with a <dcl-wrapper [type]="t"></dcl-wapper> component described in this answer

I'm trying to add a remove button to the component so I could remove the component on button click with myCompArray.splice(index, 1) but it allways removes the last one
here is my plunker http://plnkr.co/edit/4lhuHF?p=preview

Community
  • 1
  • 1
Joe B
  • 738
  • 7
  • 28

1 Answers1

0

Pass the index, not the event. The event is null because no value was emitted:

 (removed)=onRemoved(i)

You should also be aware that [index]=i updates the @Input() index; property on the remaining elements, when an item was removed or added.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I do pass `comp.instance.removed.subscribe(r => this.onRemoved(this.index));` – Joe B Nov 18 '16 at 16:28
  • I find your code a bit confusing. You pass the index through the whole application but you already have it available where you need it anyway. I think the main confusion is (as I already added to my answer) that `@Input() index;` gets updated by `ngFor` when an item is removed. – Günter Zöchbauer Nov 18 '16 at 16:31
  • I write out in the console which index I'm going to remove and even I get 0 it removes the last one – Joe B Nov 18 '16 at 16:36
  • It doesn't remove the last one, but `*ngFor` updates the `index` and the first item (previously the 2nd) gets `[index]="0"` and the 2nd (previously the 3rd) `[index]="1"` assigned and then there is no item with `[index]="2"` anymore. – Günter Zöchbauer Nov 18 '16 at 17:18
  • I know the index changes, its the position in array; but look at my updated plunker you'll c that that initially each text box has a different value so you can see when you remove the middle one that last one will fall off – Joe B Nov 21 '16 at 16:31
  • I see it now. I tried to figure out what's going on but failed so far. – Günter Zöchbauer Nov 21 '16 at 16:54
  • It seems to be related to how equality works. If you use different types `[C1, C2, C3]` it behaves differently or if you wrap the types in object literals http://plnkr.co/edit/tNXJAt?p=preview. Deleting at the end works but at the beginning or in the middle, all elements after the deleted are recreated. – Günter Zöchbauer Nov 21 '16 at 17:02