我有对象表(帐单=>帐单=>产品=>产品)。它们每个都包含另一个使用管道进行过滤的表。管道过滤可以正常工作,但是在过滤阵列之后,即使它们没有显示任何过滤结果,它们的名称(bill.name
)仍然可见。我该如何解决这个问题?
<span class="search-span">
<input [(ngModel)]="searchText" placeholder="Start typing a product name..." class="search-input">
</span>
</div>
<hr>
<ng-container *ngFor="let bill of bills; let i = index">
<div class="col-xs-12" *ngIf="bill.products?.length > 0">
<h5>
{{bill.name}} {{i === 0 ? '(this bill group)' : ''}}
</h5>
</div>
<div class="col-xs-3" *ngFor="let product of bill.products | filter : searchText">
<div [class.selected]="isProductSelected(product)" (click)="selectProduct(product)">
<span class="text">{{product.name}}</span>
</div>
</div>
</ng-container>
管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any, searchText: string): any {
if (!items) return [];
if (!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter(it => {
return it.name.toLowerCase().includes(searchText);
});
}
}
答案 0 :(得分:0)
将已过滤产品的声明移至<ng-container>
<ng-container *ngFor="let bill of bills; let i = index">
<ng-container *ngIf="(bill.products | filter : searchText) as filtered">
<ng-container *ngIf="filtered.length else noProducts">
<div class="col-xs-12">
<h5>
{{bill.name}} {{i === 0 ? '(this bill group)' : ''}}
</h5>
</div>
<div class="col-xs-3" *ngFor="let product of filtered">
<div [class.selected]="isProductSelected(product)" (click)="selectProduct(product)">
<span class="text">{{product.name}}</span>
</div>
</div>
</ng-container>
</ng-container>
</ng-container>
<ng-template #noProducts>
<span>No Products Found</span>
</ng-template>
您可以嵌套多个<ng-container>
,并且可以使用*ngIf="XXX as YYY"
语法来应用条件并将结果存储在新的模板变量中。