Search code examples
angularangular-ng-if

I can't get my angular 6 *ngIf statement to work


I can't seem to get the *ngIf statement to work. Am I missing something? I've included the *ngIf statement in a div and then added a

tag to display the message should there not be any posts/bookings. please help :)

<div class="container">
  <div class="row">
    <div class="col-6">
      <h4>Bookings</h4>
    </div>
    <span class="col-6">
      <button 
      class="btn btn-primary float-right btn-sm" 
      routerLinkActive="active" 
      routerLink="/createBooking">
        New Booking</button>
    </span>
  </div>
  <hr>
  <div class="row" *ngIf="bookings.length > 0">
    <div class="col-12">
      <a
      href="#"
      class="list-group-item clearfix"
      *ngFor="let booking of bookings">
        <div class="float-left">
          <p class="list-group-item-text"
            >{{ booking.bookingDate }}
              <br>
              {{ booking.clientName }}
              <br>
              {{ booking.projectTitle }}
              <br>
              ${{ booking.rate }}
        </div>
        </a>
      </div>
      <p *ngIf="bookings.length <= 0">No bookings added yet!</p>
    </div>
  </div>

Solution

  • You have a *ngIf that looks like this:

    <div class="row" *ngIf="bookings.length > 0">
    

    Inside of this div, you have a nested *ngIf that looks like this:

    <p *ngIf="bookings.length <= 0">No bookings added yet!</p>
    

    Now, imagine the following simplified version of what you have:

    <div class="row" *ngIf="bookings.length > 0">
        <p *ngIf="bookings.length <= 0">No bookings added yet!</p>
    </div>
    

    When you look at this, it's clear that when bookings.length is not > 0, the top-level div will not be rendered. If the top-level div isn't rendered, it's child p cannot possibly be rendered as it's inside of a div that isn't being rendered: bookings.length cannot be both > 0 and <= 0, so the p element is never rendered.