FedeLanza
FedeLanza

Reputation: 183

How to show an element in Angular 7 only if another element has no children

I have a simple angular 7 code whose general structure is like this:

<ng-container *ngFor="let item of items">
   <ion-item *ngIf="item.isReachable()">
       ......
   </ion-item>
</ng-container>
<ion-item id="target" *ngIf="ng-container has no children">
    <ion-label>
        Text to show only if ng-container has no children
    </ion-label>
</ion-item>

May anyone tell me how I can show target element only if <ng-container> has no children? What is the condition that I have to write inside the *ngIf to obtain this effect?

items is a non-empty array, so I cannot write a condition like this *ngIf="items.length == 0" to obtain what I want. The target element should be shown only if all elements of items array don't satisfy the isReachable() condition, so only if <ng-container> has no children.

Is there a way to write this simply inside the *ngIf condition?

Upvotes: 0

Views: 1311

Answers (3)

user4676340
user4676340

Reputation:

If you want to keep it in JS, you can use a getter like so :

get hasChildren() {
  return this.items.some(item => item.isReachable());
}

For the template

<ng-container *ngFor="let item of items">
   <ion-item *ngIf="item.isReachable()">
       ......
   </ion-item>
</ng-container>
<ion-item id="target" *ngIf="!hasChildren">
    <ion-label>
        Text to show only if ng-container has no children
    </ion-label>
</ion-item>

Upvotes: 1

chaendler
chaendler

Reputation: 91

What you need is just put the "if "logic one level above the ng-container

<div *ngIf="items.isThereAnyItemUnreachable(); else target">
  <ng-container *ngFor="let item of items">
     <ion-item *ngIf="item.isReachable()">
         ......
     </ion-item>
  </ng-container>
</div>
<ng-template #target>
  <ion-item>
    <ion-label>
        Text to show only if ng-container has no children
    </ion-label>
</ion-item>
</ng-template>

Upvotes: 0

user4676340
user4676340

Reputation:

You can use just CSS to do that :

.items-container {
  border: 1px solid #ccc;
  margin: 12px;
}

.items-container:not(:empty) + ion-item {
  display: none;
}
<div class="items-container">
  <ng-container *ngFor="let item of items">
     <ion-item *ngIf="item.isReachable()">
         Here should be the items
     </ion-item>
  </ng-container>
</div>
<ion-item id="target" *ngIf="ng-container has no children">
    <ion-label>
        This text should not be displayed
    </ion-label>
</ion-item>

<div class="items-container"></div>
<ion-item id="target" *ngIf="ng-container has no children">
    <ion-label>
        Text to show only if ng-container has no children
    </ion-label>
</ion-item>

I added an items container for style, but also because you need an element to use the CSS selector (and ng-containers aren't rendered).

Upvotes: 1

Related Questions