Search code examples
angularfirebasengforangular-ng-if

ngIf - else into ngFor Angular Firestore Array Objects


I have a firestore collection called users where i have an array of objects studyList where i add the documents bought by the user.

enter image description here

What i'm trying to do is: when the user clicks on a document to check if that document is already in his studyList, if it is to show "OWNED" and if it is not to show a button to buy.

That's my HTML code for ngFor:

<div *ngFor="let document of user.studyList; index as i">
    <div *ngIf="document.id == documentId; else noOwn">
        <div class="col-md-2">
            <button class="btn btn-large" [disabled]="true">Owned</button>
        </div>
    </div>
    <ng-template #noOwn>
        <div class="col-md-2">
            <button class="btn btn-large" (click)="addToStudyList(user)">Buy</button>
        </div>
    </ng-template>
</div>

The button Buy is showed the number of times the condition is false(number of other documents in the studyList), like this:

enter image description here

What i want is to show only ONCE 'OWNED' or the Buy button. Can you help me? Thank you very much!


Solution

  • Place *ngFor in the second div and you should be fine

    <div>
     <div *ngFor="let document of user.studyList; index as i">
       <div *ngIf="document.id == documentId; else noOwn">
         <div class="col-md-2">
           <button class="btn btn-large" [disabled]="true">Owned</button>
         </div>
       </div>
     </div>
     <ng-template #noOwn>
      <div class="col-md-2">
       <button class="btn btn-large" (click)="addToStudyList(user)">Buy</button>
      </div>
     </ng-template>
    </div>