我可以通过选中一个框来删除单行。当我尝试选择多个框时,当前复选框是唯一删除的行,而前面选中的复选框。以下是我的代码。请帮忙
//Service
import {Injectable} from '@angular/core';
import {Observable} from "RxJS/Rx";
import {Http, Response, Headers} from '@angular/http';
@Injectable()
export class FoodService {
constructor(private http:Http) {
}
RemoveFood(id) {
return this.http.delete('http://example.com ' + id)
.map((response:Response) => response.json())
}
}
//食物模块
export class Food (
public count: number;
public price: number;
public location: string;
public type: string;
public selected: string;
) { }
//食物表
<tr *ngFor="let food of Food">
<td><input #{{food.count}} [(ngModel)]="food.selected" type="checkbox" (change)="checkbox(food)"></td>
<td>{{food.count}}</td>
<td>{{food.price}}</td>
<td>{{food.location}}</td>
<td>{{food.type}}</td>
</tr>
//食物成分
export class FoodComponent {
Food : Food[] = [];
constructor(private foodService: FoodService) { }
selectedFood : Food;
deleteFoodSelected() {
this.foodService.RemoveFood(this.selectedFood.id)
.subscribe(data => { console.log(data) })
}
//checkbox function
checkbox(food) {
food.selected = (food.selected) ? true: false;
this.selectedFood = food;
}
}
答案 0 :(得分:7)
替换食物表中的代码,
<td><input #{{food.count}} [(ngModel)]="food.selected" type="checkbox"></td>
<td>{{food.count}}</td>
<td>{{food.price}}</td>
<td>{{food.location}}</td>
<td>{{food.type}}</td>
</tr>
<button (click)="deleteFoodSelected()">DeleteSelectedFood</button>
在食物模块中,
export class Food (
public Id: number;
public count: number;
public price: number;
public location: string;
pubic type: string;
public selected: string;
){}
在食物成分中,
selectedFood : Food[];
deleteFoodSelected(){
this.selectedFood= this.Food.filter(_ => _.selected);
for (var food in this.selectedFood) {
this.foodService.RemoveFood(this.selectedFood[food].Id)
.subscribe(data =>{
console.log(data)
}
)
}
}
//在service.ts
import {Injectable} from '@angular/core';
import {Observable} from "RxJS/Rx";
import {Http, Response, Headers} from '@angular/http';
@Injectable()
export class FoodService {
constructor(private http:Http) {
}
RemoveFood(id) {
return this.http.delete('http://example.com ' + id)
.map((response:Response) => response.json())
}
}