Search code examples
angularngforangular-ng-if

if else inside of the ngFor loop in Angular 8+


I wonder if there's an option for putting if else statement inside of the for loop.

I have example here if there's an any chance of converting this PHP code to angular.

PHP EXAMPLE

while($row = mysqli_fetch_array($query)) {
   $section = $row['name'];

   if($section_id == "TEST_ID") {
      $section = "APPROVED";
   }
   else {
      $section = "DECLINED";
   }

   echo $section;

}

ANGULAR CODE

NOTE: This is a example code only for the reference.

<tr *ngFor="let student of students">
    <td>{{ student.student_id | uppercase }}</td>
    <td>{{ student.name }}</td>
    <td>{{ student.section }}</td>
    <td><button class="btn btn-sm btn-primary btn-block" (click)="edit(student)">EDIT</button></td>
    <td><button class="btn btn-sm btn-danger btn-block" (click)="delete(student)">DELETE</button</td>
</tr>

I do research about this problem but I'm so confused since I'm a beginner in this framework. Please help me out of this problem, thank you.


Solution

  • Yes you can do with directives

    <tr *ngFor="let student of students">
        <td>{{ student.student_id | uppercase }}</td>
        <td>{{ student.name }}</td>
        <td *ngIf="student.sectionId == TestID">APPROVED</td>
        <td *ngIf="student.sectionId != TestID">DECLINED</td>
        <td><button class="btn btn-sm btn-primary btn-block" (click)="edit(student)">EDIT</button></td>
        <td><button class="btn btn-sm btn-danger btn-block" (click)="delete(student)">DELETE</button</td>
    </tr>