角度:隐藏元素

时间:2018-11-22 01:19:09

标签: angular observable

我正在从API获取json数据。之后,我用这些数据制作表格。

getValues(): Observable<Value[]> {
    return this.http.get<Value[]>(this.valuesUrl);
}

component.html

    <table>
        <thead>
            <tr>
                <th></th>
                <th>Category</th>
                <th>Product</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody *ngFor="let value of values">
            <tr *ngFor="let sku of value.skus">
                <td><input type="checkbox" value="{{sku.id}}"></td>
                <td>{{value.group.name}}</td>
                <td>{{sku.name}}</td>
                <td class="price">{{sku.price}}</td>
            </tr>
        </tbody>
    </table>
<button class="btn" (click)="addToCart()">Add to cart</button>

我已选中表中所有条目的复选框。单击按钮后,我需要从读取的数组中删除选中的条目。我想我应该使用过滤器来做到这一点,但我会出现无法读取过滤器属性的错误。

2 个答案:

答案 0 :(得分:0)

您可以使用*ngIF隐藏元素,并在循环中使用<ng-container>

<ng-container *ngFor="let sku of value.skus">
   <tr *ngIF="!sku.isAddedToCart">
     <td><input type="checkbox" value="{{sku.id}}"></td>
     <td>{{value.group.name}}</td>
     <td>{{sku.name}}</td>
     <td class="price">{{sku.price}}</td>
   </tr>
</ng-container>

使用sku.isAddedToCart为布尔值(例如)。

答案 1 :(得分:0)

我创建了一个示例来详细说明。

标记:

<table>
    <thead>
        <tr>
            <th></th>
            <th>Category</th>
            <th>Product</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody *ngFor="let value of values; let i = index;">
        <tr>
            <input type="checkbox" (change)="addChecked(i, $event.target.checked)"/>
            <td>Delete</td>
            <td>{{value}}</td>
        </tr>
    </tbody>
</table>
<button (click)="delete()">Delete</button>

逻辑:

export class App {
    values = [1, 2, 3, 4];
    checked = [];

    constructor() {
    }

    addChecked(i, isChecked) {
        isChecked ? this.checked.push(i) : this.checked.splice(i, 1);
    }

    delete() {
        for (var i = this.checked.length - 1; i >= 0; --i) {
            this.values.splice(this.checked[i], 1);
        }
        this.checked = [];
    }
}

我们假设从API提取的数据存储在values数组中并显示在表中。每行都有一个复选框以选择一行,并在复选框中更改checked数组中的添加/删除项。 checked数组存储行/值的索引。 表末尾的删除按钮与delete()方法绑定。单击后,遍历checked数组并从values数组中删除项目,更改将自动反映出来。

每次slice方法索引值从数组中删除时,循环都会反向。

这里是Plnkr:Angular delete item from table

相关问题