0

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.

2 Answers2

0

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>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Thank you so much Sir, but I wonder why how can I put the else statement since this example is for if statement only. Thank you – pacificskybeachresort May 07 '20 at 07:07
  • I don't consider this as acceptable answer because the ngIf statement is tested twice in every iteration and this can be costly in some situation – Adel Ben Hamadi Oct 16 '22 at 09:52
  • the acceptbale answer might be this https://stackoverflow.com/questions/48515267/angular-ng-template-with-parameter-inside-ngif-inside-ngfor – Adel Ben Hamadi Oct 16 '22 at 10:11
0

use NgTemplateOutlet and ngTemplateOutletContext

<tr *ngFor="let student of students">
<td>{{ student.student_id | uppercase }}</td>
<td>{{ student.name }}</td>
<ng-container [ngTemplateOutlet]="student.sectionId == TestID  ? approved: 
             declined" [ngTemplateOutletContext]="{student:student}">
</ng-container>
<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>
<ng-template #approved let-s="student">
<td>APPROVED</td>
</ng-template>
<ng-template #declined let-s="student">
<td>DECLINED</td>
</ng-template>
Adel Ben Hamadi
  • 720
  • 10
  • 13