Reputation: 99
I try to write a method to delete and add item to array i need delete and add methods in a easy way because i am not familiar typescript
export class NgForComponent implements OnInit {
Sayilar: number[];
constructor() {
this.Sayilar = [1, 2, 3, 4, 5];
}
ngOnInit() {
}
}
html
<div>
<ul>
<li *ngFor="let sayi of Sayilar">
{{sayi}}
</li>
</ul>
</div>
<button >Delete</button>
Upvotes: 0
Views: 88
Reputation: 118
<ul>
<li *ngFor="let sayi of Sayilar">
{{sayi}}
<button (click)="delete(sayi)">Delete</button>
</li>
</ul>
and your ts
delete(sayi){
this.Sayilar.filter(m => m !== sayi)
}
Upvotes: 0
Reputation: 222542
you need to place the delete within the ngFor inorder to get the clicked item, otherwise you would not know which item to delete , or change your interface in order to identify which item to be deleted.
<ul>
<li *ngFor="let sayi of Sayilar">
{{sayi}}
<button (click)="delete(sayi)">Delete</button>
</li>
</ul>
and then in TS,
delete(item : any){
this.Sayilar.splice(item ,1);
}
Upvotes: 0
Reputation: 262
<li *ngFor="let sayi of Sayilar;let i = index">
{{sayi}}
<button (click)="deleteSayilar(i)">Delete</button>
</li>
in typescript
deleteSayilar(i){
this.Sayilar.splice(i,1);
}
Upvotes: 2