Search code examples
angular5ngforangular-ng-if

Loop over response objects based on condition angular 5


I have a rest response which i want to loop over but based on condition, here's my response:

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

I want in the UI to show only one object based on veichleModel if user searched by M3 then display that object response in the table, else show 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>

Solution

  • You need to do two things here :

    1. Add some variable to store the selected model M1 or M3
    2. Add condition inside loop to display respective object properties (Make use of ng-container)

    Doing so, you can scale your array to 100 or more objects

    template

    <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 file

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