bluePearl
bluePearl

Reputation: 1257

using *ngIf as a toggle to display div content in angular 2

I have a div that contains a dropdown box and i would by default the dropdown box is empty and only populated as the user removes items from the view page. I would like to have this div with the dropdown to be not visible when the list is empty and to be displayed once the list has at least 1 item.

<div class="btn-group bootstrap-select show-tick">
   <button type="button" class="btn dropdown-toggle bs-placeholder btn-default" (click)="toggleSelect()">
       <span class="pull-left">List Items</span>&nbsp;
       <span class="bs-caret ">
           <span class="caret "></span>
       </span>
   </button>
        <ul class="dropdown-menu multi-select-popup " [ngStyle]="{display:isOpen ? 'block' : 'none'} " style="display:block; ">
            <li *ngFor="let item of dropdownlist; let i = index ">
                <a (click)="select(item, i) " class="dropdown-item ">
                    <i class="fa fa-fw " [ngClass]="{ 'fa-check': item.checked, 'glyphicon-none': !item.checked} "></i>
                    <span [innerHtml]="item.title "></span>
                </a>
            </li>
        </ul>
    </div>

how can i implements this using *ngIf to toggle the display of the div depending on the length of items in the dropdown.

Upvotes: 2

Views: 2573

Answers (2)

msanford
msanford

Reputation: 12227

Use a combination of the safe navigation operator and *ngIf:

<ul *ngIf="dropdownlist?.length > 0" ... >

This will access the length property of dropdownlist, if it is defined, and will satisfy the condition if the length is > 0.

Using the safe accessor saves you having to chain dropdownlist && dropdownlist.length since it won't throw an exception if dropdownlist is undefined.

Upvotes: 3

Pezetter
Pezetter

Reputation: 2862

<div class="btn-group bootstrap-select show-tick">
<button type="button" class="btn dropdown-toggle bs-placeholder btn-default" (click)="toggleSelect()">
    <span class="pull-left">List Items</span>&nbsp;
    <span class="bs-caret ">
        <span class="caret "></span>
    </span>
</button>
      <ul *ngIf="dropdownlist?.length" class="dropdown-menu multi-select-popup " [ngStyle]="{display:isOpen ? 'block' : 'none'} " style="display:block; ">
          <li *ngFor="let item of dropdownlist; let i = index ">
              <a (click)="select(item, i) " class="dropdown-item ">
                  <i class="fa fa-fw " [ngClass]="{ 'fa-check': item.checked, 'glyphicon-none': !item.checked} "></i>
                  <span [innerHtml]="item.title "></span>
              </a>
          </li>
      </ul>
  </div>

Upvotes: 1

Related Questions