SKL
SKL

Reputation: 1443

angular2 - show hide if value is empty

Here I have two container, first container suppose to be show if value is exist in json and second one show is value is empty from json. Here is my code:

App.component.html

<!-- show this container if value is exist -->
    <ng-container *ngIf="outletName">
  <div class="media media-xs align-items-center mb-5">
    <div class="media-right float-right">
      <a class="drop-assigned-outlet" href="#"><i class="fa fa-trash-o"></i></a>
    </div>
    <button class="btn btn-primary-ln" *ngIf="outletName">Change assigned outlet</button>x
  </div>
</ng-container>

<!-- show this container if value is empty -->
<ng-container *ngIf="outletName == ''">
  <div class="media media-xs align-items-center mb-5">
    <p>No outlet have assigned</p>
  </div>
  <button class="btn btn-primary-ln">Assign an outlet</button>
</ng-container>

data.json

[
  {
    "staffId": "59998eeadfb23a8c0bba5769",
    "staffName": "Sutton Fitzpatrick",
    "outletName": "Marjorie Fitzgerald",
    "outletId": "59998eeaf84372166a233235",
    "outletLocation": "mid valley, kl",
    "designation": "Outlet Supervisor",
    "image": "http://placehold.it/100x100",
    "activeSince": "2015-06-27T09:29:23 -08:00",
    "deactivatedSince": "2015-12-07T12:05:04 -08:00",
    "status": "active",
    "email": "[email protected]",
    "contact": 60124174701,
    "devices": [
      {
        "posName": "Outlet1_DEVICE00001",
        "deviceId": "59998eea245ec74623bfb06c",
        "lastActive": "04:50:34"
      }
    ]
  }
]

app.component.ts

ngOnInit() {

    let staffDetail = localStorage.getItem('editStaff');
    let staff = JSON.parse(staffDetail);

    this.outletName = staff.dataItem.outletName;
    this.outletLocation = staff.dataItem.outletLocation;
    this.image = staff.dataItem.image;
}

Upvotes: 1

Views: 6894

Answers (2)

Vega
Vega

Reputation: 28701

Here you have 'perfect' occasion to use ng-templates:

 <div *ngIf="outletName; else templateForEmpty">
          <div class="media media-xs align-items-center mb-5">
              <div class="media-right float-right">
                 <a class="drop-assigned-outlet" href="#"><i class="fa fa-trash-o"></i></a>
              </div>
             <button class="btn btn-primary-ln" *ngIf="outletName">Change assigned outlet</button>x
           </div>
           <ng-template #templateForEmpty>
              <div class="media media-xs align-items-center mb-5">
                 <p>No outlet have assigned</p>
              </div>
              <button class="btn btn-primary-ln">Assign an outlet</button>
           </ng-template>
   </div>

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657048

Change the first to

<ng-container *ngIf="outletName !== ''">

Upvotes: 5

Related Questions