我有一个Requirement对象数组和一个产品对象数组。每个需求与产品有一对多的关系,即一个需求有多个产品。每个产品对象都有一个需求对象,通过访问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>
模板遍历每个需求,然后填充每个需求的products表。我使用一个自定义的管道来过滤每个需求的产品。
以下是我的自定义管道的代码
@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个产品。但是每次我加载页面时,只有两个来自任何一个需求的产品被显示,而其他两个产品没有出现在表格中。
请注意,之前我使用以下代码对表中的每个<td>
元素使用*ngIf得到了预期的结果
<td *ngIf = "product.requirement.id===requirement.id">{{product.name}}</td>
我该如何解决这个问题。请帮帮忙
发布于 2018-11-22 07:37:23
为什么不在tr上使用*ngIf就可以了呢?老实说,我会通过使用地图对数据进行预排序来解决这个问题,但我看不出为什么tr上的单个*ngIf不起作用。
无论如何,您的管道无法工作,因为您需要一个不纯的管道,并且您必须显式地将该管道标识为不纯管道。请参阅https://angular.io/guide/pipes#pure-and-impure-pipes
https://stackoverflow.com/questions/53421568
复制相似问题