Search code examples
javascriptangulartypescriptdropdown

custom dropdown only displayed selected value Angular


I using custom dropdown using div,when I got object response cards from API, I need to iterate data using custom dropdown, problem is after selected, the next clicked dropdown only show selected value ( supposed to be array object), this is what I had tried:

ts file

  selectSavedCard() {
    this.show = !this.show;
  }

  selectDropdownCard(card) {
    this.myData.cards.find((item) => item.cardId === card.id) ?
    this.myData.cards = this.myData.cards.filter((item) => item.cardId === card.id) :
    this.myData.cards= [card];
    this.show = false;
    this.hasSelected = true;
    this.selectedCard = card;
    this.show1 = true;
  }

html file

  <div class="div1" (click)="selectSavedCard()" [(ngModel)]="selectedCard" ngDefaultControl>
    <div *ngIf='!hasSelected'>
      <div>
        <p>dropdown</p>
      </div>
    </div>

<!-- to bind selected card -->
<ng-container *ngIf="show1">
      <div  *ngFor="let card of myData.cards">
      <div>
        <p>{{card.cardNumberMasked}}  dropdown</p>
      </div>
    </div>
</ng-container>
  </div>

    <div class="div2" *ngIf="show">
    <div *ngFor="let card of myData.cards" (click)="selectDropdownCard(card)">
      <div>
        <p>{{card.cardNumberMasked}}</p>
      </div>
    </div>
  </div>

this is my stackblitz demo, for the first clicked dropdown, it worked well (it show all array) after selected card, clicked drodpdown, (it only show selected card, supposed to be show all array), hope can make u guys understand and give me suggestion to solve this.


Solution

  • You have filtered and modified this.myData.cards to have only one item:

     selectDropdownCard(card) {
         this.myData.cards= [card];
      }
    

    Therefore it displays only single item.

    To push the selected item, you don't need to modify myData , you can simply display it without for loop.

    <ng-container *ngIf="show1">
        {{selectedCard.cardNumberMasked}} dropdown
    </ng-container>
    

    Removing this.myData.cards= [card]; will display all items

    Forked Stackbiltz