如何通过单击按钮Angular 2从表中删除特定行

时间:2017-08-18 13:15:59

标签: javascript angular html-table

我试图通过单击for循环中该行的按钮来删除特定行,但是它会删除该表的所有行。

这是我的Html代码:

<table id="mytable" class="table table-bordred table-striped">
    <tbody id="del">
        <tr *ngFor="let cart of modalData">
            <td>
                <div style="display:inline-flex;">
                    <div style="margin-left:10px;">
                        <p class="font_weight" style="font-size:13px;">{{cart.ExamName}}</p>
                        <p>{{cart.Categoryname}}|{{cart.CompanyName}}</p>
                    </div>
                </div>
            </td>
            <td>
                <div style="margin-top: 32px;">
                    <p class="font_weight" style="font-size:13px;"></p> <span class="font_weight" style="font-size: 13px;"> {{cart.Amount| currency :'USD':'true'}} </span> </div>
            </td>
            <td>
                <div style="margin-top: 19px;">
                    <button class="button_transparent" (click)="Delete(cart)"> delete </button>
                </div>
            </td>
        </tr>
        <tr> </tr>
    </tbody>
</table>

这是我的组件:

public loadData() {       

                let transaction = new TransactionalInformation();
                this.myCartService.GetExamOrderForCart()
                    .subscribe(response => this.getDataOnSuccess(response),
                    response => this.getDataOnError(response));          

        }

    getDataOnSuccess(response) {       
        this.modalData = response.Items;
        }

这是我的删除方法:

public Delete(response) {
     this.myCartService.updateExamOrder(response)
     .subscribe(response => this.getDataOnSuccessForDelete(response),
     response => this.getDataOnErrorForDelete(response));
} 

请帮我做,如何从表中只删除一行?

2 个答案:

答案 0 :(得分:3)

您可以在* ngFor:

中添加index
<tr *ngFor="let cart of modalData;let i = index">

然后,在方法中传递索引:

<button class="button_transparent" (click)="delete(i)"> delete </button>

最后:

delete(i){
  this.modalData.splice(i,1);
}

答案 1 :(得分:1)

你可以这样做:

<button class="button_transparent" (click)="delete(cart)"> delete </button>

然后

delete(item){
    this. modalData = this. modalData.filter(item => item.id !== id);
    this.modalData.push();}

这里您要创建一个没有要删除的元素的新列表。