我尝试编写一种删除和添加项目到数组的方法,我需要一种简单的删除和添加方法的方法,因为我不熟悉打字稿
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>
答案 0 :(得分:2)
<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);
}
答案 1 :(得分:0)
您需要将删除放置在ngFor内,以便获得被单击的项目,否则您将不知道要删除哪个项目,或者更改界面以标识要删除的项目。
<ul>
<li *ngFor="let sayi of Sayilar">
{{sayi}}
<button (click)="delete(sayi)">Delete</button>
</li>
</ul>
然后在TS中
delete(item : any){
this.Sayilar.splice(item ,1);
}
答案 2 :(得分:0)
<ul>
<li *ngFor="let sayi of Sayilar">
{{sayi}}
<button (click)="delete(sayi)">Delete</button>
</li>
</ul>
和您的ts
delete(sayi){
this.Sayilar.filter(m => m !== sayi)
}