I have created an empty array that I use to loop through to dynamically add and remove text-boxes on my form.
mobiles: Array<string> = [];
<ng-container *ngFor="let mobile of mobiles; index as i">
// Code
</ng-container>
Outside the loop, I have a button to add a new text-box.
<button (click)="addElement()">
</button>
And I have a button inside the loop to remove the specific text-box, based on the index.
<button (click)="removeElement(i)">
</button>
The addElement() function simply pushes an empty value to the end of the array.
this.mobiles.push('');
While the removeElement(index) function removes the index from the array.
if (index in this.mobiles) {
this.mobiles.splice(index, 1);
}
The issue with this code is that since all values on my array are the same (empty), splice() is not removing the element at the specified index but rather the last element in the array. And as such, it's also removing the last text-box instead of the one I click.
I tested pushing non-empty values in my array but the result is still the same. It only works correctly if I push distinct values, for example:
this.mobiles.push(this.mobiles.length);
I do not want to use this method however, since I plan to fill this array with actual phone numbers.
Is there any alternative?
My Angular version is 7.2.15.
Thank you!