ThomasVestergaard ThomasVestergaard - 7 months ago 486
Javascript Question

Angular2 ng-if not working

I'm really new to angular, I have been through all ng-if questions and cannot seem to find the right answer.

I have this:

<tr *ngFor="#position of positions">
<td>
<div ng-if="position.way == 0">Long</div>
<div ng-if="position.way == 1">Short</div>
{{position.way}}
</td>
</tr>


{{position.way}} is outputting either 1 or 0 as expected and is defined as a string in the model. But the two div's are both displayed no matter what position.way is.

I have tried wrapping 0 and 1 in quotes, I have tried tripple equality operator, same result.

What am I doing wrong here?

Answer

The ng-if syntax is wrong. It should be:

<tr *ngFor="#position of positions">                               
<td>
 <div *ngIf="position.way == 0">Long</div>
 <div *ngIf="position.way == 1">Short</div>
 {{position.way}}
 </td>
</tr>

you also might want to utilize the safe-navigation operator

<tr *ngFor="#position of positions">                               
<td>
 <div *ngIf="position?.way == 0">Long</div>
 <div *ngIf="position?.way == 1">Short</div>
 {{position?.way}}
 </td>
</tr>

to not get an exception when position is null or undefined. Might not be necessary if you initialize position in the constructor synchronous.