Search code examples
angularionic-frameworkngforangular-ng-ifng-template

Is it possible to use ngIf to match two arrays and show correctly the parameters that don't match?


I have an item that need to be filtered to show if it's available or not. I am using a toggle because it has to be dynamic. The problem is that I have a function call that sends me an array of the titles that are available to show it with the toggle.

<ion-item *ngFor="let serVivo of seresVivos" id="items">
<div *ngFor="let available of availables">  
  <ng-template *ngIf="available === serVivo.title;then showBlock; else notShowBlock">
  </ng-template>
  <ng-template #showBlock>
    <ion-toggle  (ionChange)="change(serVivo.title, $event)" checked ></ion-toggle>
  </ng-template>
  <ng-template #notShowBlock>
    <ion-toggle  (ionChange)="change(serVivo.title, $event)"  ></ion-toggle>
  </ng-template>
</div>    
</ion-item>

As it can only match once, when the title matches one item of the array it shows the toggle correctly. However as the ones which doesn't match are all the rest, so it creates the same items as it has the array available. Result with the actual code.The result only creating the true toggles


Solution

  • The following should go through seresVivos array, show the serVivo's title and show toggle as checked if serVivo.title is in availables array.

    <ion-item *ngFor="let serVivo of seresVivos" id="items"> 
        {{serVivo.title}}   
        <ion-toggle *ngIf="availables.includes(serVivo.title)" (ionChange)="change(serVivo.title, $event)" checked ></ion-toggle>
    </ion-item>
    

    But I think that in order to avoid the includes logic in template a better solution is to process arrays in the ts-file and add something like seresVivo.available boolean field to each seresVivo.