【问题标题】:Angular Custom Pipe for filtering Arrays用于过滤数组的 Angular 自定义管道
【发布时间】:2018-11-21 22:53:45
【问题描述】:

我有一个需求对象数组和产品对象数组。每个需求都与产品有一对多的关系,即一个需求有多个产品。每个产品对象中都有一个需求对象,从这个需求对象中我们可以通过访问requirement.id值来找出它属于哪个需求。

现在我有了这个 HTML 模板

<div class="row" *ngFor="let requirement of requirements; let i= index">
  <div class="col-md-12" style="margin-bottom: 15px;">
    <h3 style="display: inline">{{requirement.title}}</h3>

    <table class="table table-bordered table-hover">
      <tr>
        <th>Product Name</th>
        <th>Unit Cost</th>
        <th>Qty</th>
        <th>Unit</th>
        <th>Total Cost</th>
        <th>Product Profit</th>
        <th>Product VAT</th>
        <th>Total Price</th>
      </tr>
      <tr *ngFor="let product of products | productFilter: requirement">
        <td>{{product.name}}</td>
        <td>{{product.unitCost}}</td>
        <td>{{product.qty}}</td>
        <td>{{product.unit}}</td>
        <td>{{product.totalCost | number:'.'}}</td>
        <td>{{product.profit | number:'.'}}</td>
        <td>{{product.vat | number:'.'}}</td>
        <td>{{product.totalPrice | number:'.'}}</td>
      </tr>
      <tr>
        <td colspan="7"><strong>Sub-Total</strong></td>
        <td><strong>{{requirement.requirementTotal}}</strong></td>
      </tr>
    </table>
  </div>
</div>

模板循环遍历每个需求,然后为每个需求填充产品表。我正在使用自定义管道来过滤每个要求的产品。

这是我的自定义管道的代码

@Pipe({
  name: 'productFilter'
})
export class ProductFilterPipe implements PipeTransform {
  transform(products: Product[], requirement: Requirement): Product[] {
    const filteredProducts = products.filter(product => product.requirement.id === requirement.id);
    return filteredProducts;
  }
}

但这并没有给我预期的结果。我在需求数组中有两个需求,在产品数组中有 4 个产品。每个需求有 2 个产品。但是每次我加载页面时,任何一个需求中只有 2 个产品会显示,而其他两个产品没有显示在表格中。

请注意,之前我对每个都使用 *ngIf 得到了我想要的结果 &lt;td&gt; 我的表格的元素使用下面的代码

<td *ngIf = "product.requirement.id===requirement.id">{{product.name}}</td> 

我该如何解决这个问题。请帮忙

【问题讨论】:

标签: angular angular-pipe


【解决方案1】:

为什么不直接在 tr 上使用 *ngIf 并完成呢?老实说,我会通过使用地图对数据进行预排序来解决它,但我看不出为什么 tr 上的单个 *ngIf 不起作用。

无论如何,您的管道不起作用,因为您出于您的目的需要一个不纯的管道,并且您必须明确地识别该管道。见https://angular.io/guide/pipes#pure-and-impure-pipes

【讨论】:

  • 非常感谢。把它变成不纯的管道确实解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-13
相关资源
最近更新 更多