Search code examples
angulartypescriptdropdownngfor

selected only one value dropdown on custom dropdown Angular


I using my own custom dropdown which I need to using selected only one value , it supposed to be when I clicked Dropdown1, div will displayed Dropdown1, when I clicked Dropdown2 it will replaced Dropdown1 in div. this is stackblitz link I created,

ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  savedCards = [];
  show = false;
  hasSelected: boolean;

    savedCreditCards = [
    { id: '001', viewValue: 'Dropdown1' },
    { id: '002', viewValue: 'Dropdown2' },
    { id: '003', viewValue: 'Dropdown3' },
    { id: '004', viewValue: 'Dropdown4' },
  ];

  ngOnInit() {
  }

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

  selectDropdownCard(card) {
    this.savedCards.find((item) => item.id === card.id) ?
      this.savedCards = this.savedCards.filter((item) => item.id === card.id) :
      this.savedCards.push(card);
    this.show = false;
    this.hasSelected = true;
  }

}

html

  <div class="div1" (click)="selectSavedCard()">
    <div *ngIf='!hasSelected'>
      <div>
        <p>dropdown</p>
      </div>
    </div>
    <div *ngFor="let card of savedCards">
      <div>
        <p>{{card.viewValue}}</p>
      </div>
    </div>
  </div>
  <div class="div2" *ngIf="show">
    <div *ngFor="let card of savedCreditCards" (click)="selectDropdownCard(card)">
      <div>
        <p>{{card.viewValue}}</p>
      </div>
    </div>
  </div>

I know it can be done with set savedCards array as empty but I believe it not the best practice, Need opinion and suggestion,


Solution

  • To show only single card which was selected, instead of pushing it into array. Just create a new array with single item. Which means in your selectDropdownCard method

    replace this this.savedCards.push(card); with this.savedCards = [card];