Search code examples
loopsangular6ngforangular-ng-if

Angular 6 check for the existence of a variable with ngIf


How can I check for the existence of a value in angular 6 with ngIf in a nested json object? I have this Json returned from an api call:

 {

 "orth": ["axxam"],

 "gram":[
      {"pos": ["isem"],
       "feminine": ["taxxamt"],
       "plural":"ixxamen"}
        ]
  }

I managed to get the values for "orth" and "pos". What I cannot get is this: I want first to test if the pos == isem, if and only if this is true, then I will show the values for "feminine" and "plural". Here is the code so far:

 <span> spelling: {{elements?.orth}}</span> 
 <span> POS: {{elements?.gram[0].pos}}</span>

The following is not working:

  <span *ngIf="elements?.gram[0].pos===isem"> POS: 
 {{elements?.gram[0].feminine}}</span>

Additionally, can I loop through the object? I tried this with no results:

 <span *ngFor="let element of elements.gram | keyvalue">
  {{element.key}}: {{element.value}}

Solution

  • You were very close. :)

    In the first <span> that is not working, elements?.gram[0].pos is actually an array, so should be referenced like this: elements?.gram[0].pos[0]. Also to compare a string you need to enclose the string in quotes, as you wrote it the code will attempt to compare elements?.gram[0].pos to a variable named isem. Put those together and it would look like this:

    <span *ngIf="elements?.gram[0].pos[0]==='isem'"> 
        POS: {{elements?.gram[0].feminine}}
    </span>
    

    For your loop, elements?.gram is an array with only one element, which is an object - that object contains three elements. If you want to iterate through the object that is inside the array, specify your *ngFor like this:

    <span *ngFor="let element of elements?.gram[0] | keyvalue">
        {{element.key}}: {{element.value}}
    </span>
    

    Here is a Working Stackblitz showing this in action.

    I hope this helps.