Angular: Display nothing incase *ngIf fails

Viewed 290

I have two arrays fetchedData and cardCheckArray. I am using nested loop and displaying the data of the fetchedData if some certain element in the fetchedData equals the cardCheckArray. It's kind of displaying subitems of an array but by using two different arrays. I am getting an issue here. Incase, if the element of the first array doesn't match with the second array, the Angular prints nothing but still occupies an empty line for each iteration when the condition fails. This is putting a lot of space under each card header. I want to somehow don't print empty whitespace if *ngIf fails. I have tried using ng-template but still getting the same issue.

Here's my code:

HTML

<div *ngIf = "containsData">
    <div class="card-body">
      <div style = "width: 70%; margin: auto;" *ngFor = "let data of cardCheckArray; let i = index">
        <div class="card-header">
          <p>{{data}}</p>
        </div>
        <div class="card-body" *ngFor = "let data2 of fetchedData">
          <div *ngIf = "data2.PROCESS_NAME == data; else printNothing">
            <p>{{data2.DOCUMENT_NAME}}</p>
            <p>{{data2.DATE_SUBMITTED | date: 'medium'}}</p>
            <p>{{data2.PROCESS_NAME}}</p>
          </div>
          <ng-template #printNothing>
            <p>empty</p>        //I am printing empty right now but it prints whitespaces if I leave it blank here
          </ng-template>
        </div>
      </div>

      <hr>
    </div>
  </div>

typescript

var swap = this.fetchedData[0].PROCESS_NAME;

      for (var x in this.fetchedData)
      {
        if(swap == this.fetchedData[x].PROCESS_NAME)
        {
          continue;
        }
        else
        {
          this.cardCheckArray.push(swap);
          swap = this.fetchedData[x].PROCESS_NAME;
        }
      }
this.cardCheckArray.push(swap);

How can I resolve this? Any help would be appreciated. Thanks!

2 Answers

Angular still renders the div element with the ngFor directive. Since you cannot put two structural directives (ngFor and ngIf) on the same element you should use an ng-container. Its an element where you can place a structural directive (ngFor in your case), but which will not be rendered in the html. Inside that put your div with card-body class and put the ngIf on it.

Use ng-container for *ngFor and do not use else and ng-template.

<ng-container "let data2 of fetchedData" >
  &lt;div class="card-body" *ngIf = "data2.PROCESS_NAME == data; else printNothing">
     …
Related