ng用于匹配键值

时间:2018-10-30 18:39:27

标签: angular

在角度6中,使用ngFor,是否可以匹配键值并打印 什么时候匹配?

下面是我的JSON,我想匹配SportName并打印名称以匹配记录

例如,我要检查sportName =“ shooting Indoor”并仅打印Name =“ Ian”。休息应该被忽略。

[{
  "SportName": "football Outdoor",
  "Name": "Ami",
}, {
  "SportName": "shooting Indoor",
  "Name": "Ian",
}, {
  "SportName": "hockey Outdoor",
  "Name": "Jeo",
}];

2 个答案:

答案 0 :(得分:2)

使用这样的代码(我从头开始写)-我假设您的数组位于this.list

<div *ngFor="let item of list">
    <div *ngIf="item.SportName =='shooting Indoor' ">
        {{ item.Name }}
    </div>
</dvi>

如果您不想生成<div>节点,请改用<ng-container>

答案 1 :(得分:0)

考虑到您的组件中有sports

...
sports = [
  { "SportName": "football Outdoor", "Name": "Ami" },
  { "SportName": "shooting Indoor", "Name": "Ian" },
  { "SportName": "hockey Outdoor", "Name": "Jeo" }
];
...

ng-container *ngFor 一起使用 *ngIf ,并检查< strong> *ngIf

<div *ngFor="let sport of sports">
    <ng-container *ngIf="sport.SportName === 'shooting Indoor' && sport.Name='Ian'">
        {{ sport.Name }}
    </ng-container>
</div>

OR

您可以使用 [ngStyle]

<div 
  *ngFor="let sport of sports" 
  [ngStyle]="{ display : (sport.SportName === 'shooting Indoor' && sport.Name='Ian') ? 'block': 'none' }">
  {{ sport.Name }}
</div>