首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 9-尝试遍历对象列表并验证

Angular 9-尝试遍历对象列表并验证
EN

Stack Overflow用户
提问于 2020-06-09 09:21:05
回答 1查看 47关注 0票数 1

如果这是一个非常基本的问题,很抱歉,但我只是从angular 9和json开始。我正在尝试迭代一个列表,并且仅在正确的ID与从上一个页面链接传递的ID匹配的情况下才为表创建一行

我试图让if语句在for循环中工作,但它没有产生任何结果。

代码语言:javascript
复制
  <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>

如果我执行下面的代码,我可以让它工作,但我知道这不是最优的,我找不到/找不出正确的方法

代码语言:javascript
复制
  <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>
EN

回答 1

Stack Overflow用户

发布于 2020-06-09 09:31:48

您可以使用ng-container作为循环的虚拟元素(它不会产生任何实际的html标记)。然后在其中使用*ngIf structural指令,如下所示:

代码语言:javascript
复制
<ng-container *ngFor="let tag of tags">
  <tr *ngIf="tag.id == tagged.id">
     <th>...</th>
  </tr>
</ng-container>

此外,如果需要重用这种过滤,您可以创建一个pipe

它可能看起来像这样(简单的例子):

代码语言:javascript
复制
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);
    }
}

并像这样使用:

代码语言:javascript
复制
<tr *ngFor="let tag of tags | filter:'id':tagged.id">
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62273565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档