如果这是一个非常基本的问题,很抱歉,但我只是从angular 9和json开始。我正在尝试迭代一个列表,并且仅在正确的ID与从上一个页面链接传递的ID匹配的情况下才为表创建一行
我试图让if语句在for循环中工作,但它没有产生任何结果。
<table>
<tr *ngFor="let tag of tags; if tag.id == tagged.id">
<th>{{ tag.id }}</th>
<th>{{ tag.manufacturer }}</th>
<th>{{ tag.serial }}</th>
<th>{{ tag.inspectedDate }}</th>
<th>{{ tag.result }}</th>
<th>{{ tag.actionNeeded }}</th>
<th>{{ tag.inspectee }}</th>
<th>{{ tag.certificateNumb }}</th>
<th>{{ tag.nextInspection }}</th>
</tr>
</table>如果我执行下面的代码,我可以让它工作,但我知道这不是最优的,我找不到/找不出正确的方法
<table>
<tr *ngFor="let tag of tags">
<th *ngIf="tag.id == tagged.id">{{ tag.id }}</th>
<th *ngIf="tag.id == tagged.id">{{ tag.manufacturer }}</th>
<th *ngIf="tag.id == tagged.id">{{ tag.serial }}</th>
<th *ngIf="tag.id == tagged.id">{{ tag.inspectedDate }}</th>
<th *ngIf="tag.id == tagged.id">{{ tag.result }}</th>
<th *ngIf="tag.id == tagged.id">{{ tag.actionNeeded }}</th>
<th *ngIf="tag.id == tagged.id">{{ tag.inspectee }}</th>
<th *ngIf="tag.id == tagged.id">{{ tag.certificateNumb }}</th>
<th *ngIf="tag.id == tagged.id">{{ tag.nextInspection }}</th>
</tr>
</table>发布于 2020-06-09 09:31:48
您可以使用ng-container作为循环的虚拟元素(它不会产生任何实际的html标记)。然后在其中使用*ngIf structural指令,如下所示:
<ng-container *ngFor="let tag of tags">
<tr *ngIf="tag.id == tagged.id">
<th>...</th>
</tr>
</ng-container>此外,如果需要重用这种过滤,您可以创建一个pipe
它可能看起来像这样(简单的例子):
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(arr: Array<any>, prop: string, value: any) {
return arr.filter(x => x[prop] && x[prop] === value);
}
}并像这样使用:
<tr *ngFor="let tag of tags | filter:'id':tagged.id">https://stackoverflow.com/questions/62273565
复制相似问题