The most important point is that you should not use i
on your item
.
item
is already representing each item in your list, so access it directly.
Also, you need to make your array an array of objects, so that Angular can track them. (Ideally, you would not use a simple counter for assigning id properties, this is just for demonstration purposes. You could also use that id, to delete from the array if desired, using filter etc.)
https://stackblitz.com/edit/angular-ivy-twsm7e
app.html:
<button (click)="addSome()">add</button>
<div class="form-group" *ngFor="let item of inputFields; index as i">
<h6>{{item.id}}</h6>
<input type="text" class="form-control" name="price" [(ngModel)]="item.text" />
<button (click)="deleteSome(i)">delete</button>
</div>
app.ts
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
inputFields = [];
currentId = 0;
addSome() {
this.inputFields = [...this.inputFields, {text: "", id: this.currentId}];
this.currentId ++;
console.log(this.inputFields)
}
deleteSome(val: number) {
console.log(val);
this.inputFields.splice(val, 1);
console.log(this.inputFields)
}
}
Alternative:
using id and filter instead of index and splice, to delete items:
app.html
<button (click)="addSome()">add</button>
<div class="form-group" *ngFor="let item of inputFields">
<h6>{{item.id}}</h6>
<input type="text" class="form-control" name="price" [(ngModel)]="item.text" />
<button (click)="deleteSome(item.id)">delete</button>
</div>
app.ts
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
inputFields = [];
currentId = 0;
addSome() {
this.inputFields = [...this.inputFields, {text: "", id: this.currentId}];
this.currentId ++;
console.log(this.inputFields)
}
deleteSome(id: number) {
console.log(id);
this.inputFields = this.inputFields.filter(item => item.id != id)
console.log(this.inputFields)
}
}