根据条件角度5遍历响应对象

时间:2018-09-01 09:54:03

标签: angular5 ngfor angular-ng-if

我有一个想要循环的休息响应,但根据条件,这是我的响应:

{
    "veichleType": "SUV",
    "veichleBrand": "BMW",
    "veichleModels": [{
            "veichleModel": "M3",
            "property1": "value",
            "property2": "value",
            "property3": "value"
        },
        {
            "veichleModel": "M1",
            "property": "value",
            "property2": "value",
            "property3": "value"
        }
    ]
}

如果用户被M3搜索,则我希望在UI中仅显示一个基于veichleModel的对象,然后在表中显示该对象的响应,否则显示M1。

<table>
<thead>
headings here
</thead>
<tbody *ngIf='serviceResponse.veichleModels'>
<tr *ngFor="let veichleModel of serviceResponse.veichleModels">
<td>{{veichleModels.property1}}</td>
<td>{{veichleModels.property2}}</td>
<td>{{veichleModels.property3}}</td>        
</tbody>
</table>

1 个答案:

答案 0 :(得分:1)

您需要在这里做两件事:

  1. 添加一些变量以存储选定的模型M1M3
  2. 在循环内添加条件以显示相应的对象属性(使用ng-container

这样做,您可以将数组缩放到100个或更多对象

模板

<tbody *ngIf='serviceResponse.veichleModels'>
        <tr *ngFor="let veichle of serviceResponse.veichleModels">
            <ng-container *ngIf="veichle.veichleModel == selected">
                <td>{{veichle.property1}}</td>
                <td>{{veichle.property2}}</td>
                <td>{{veichle.property3}}</td>
            </ng-container>
        </tr>
</tbody>

ts文件

export class AppComponent  {
  selected = 'M1';
  serviceResponse = {"veichleModels": [{
            "veichleModel": "M3",
            "property1": "M3val1",
            "property2": "M3val2",
            "property3": "M3val3"
        },
        {
            "veichleModel": "M1",
            "property1": "M1val1",
            "property2": "M1val2",
            "property3": "M1val3"
        }
    ]}
}