Angular feature that shows only the selected value in a custom dropdown

Using a custom dropdown created with div, I encountered an issue when receiving an object response cards from the API. The problem arises when trying to iterate through the data using the custom dropdown - after selecting an item, the next clicked dropdown only displays the selected value (instead of the array object). Here is what I have attempted:

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>

Here is my StackBlitz demo. Initially, the first clicked dropdown works as expected (displaying all items in the array). However, after selecting an item and clicking on the dropdown again, it only shows the selected card instead of displaying the entire array. Any suggestions on how to solve this are greatly appreciated.

Answer №1

You have successfully filtered and updated the contents of this.myData.cards to only contain a single item:

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

As a result, it now displays just the single selected item.

If you wish to display the selected item without modifying myData, you can do so directly without using a for loop.

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

Removing the line this.myData.cards= [card]; will cause all items to be displayed.

Visit Forked Stackbiltz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a series of linked jQuery functions

Is there a more efficient way to write this code snippet? $('#element').html( $('#element').data('test') ); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="el ...

JavaScript Reflective Toolkit

Does anyone know of a reflection library for JavaScript? I'm looking to retrieve a list of all global variables and functions, or the list of variables from an object. I am working with a tool that supports JavaScript and HTML but does not have a deb ...

Removing an element from an array within each subdocument using Mongoose

In my User Model, I have a cart that stores products (only the id). When I need to remove a product from the store, it should also be removed from all users' carts. I attempted this code: User.update({ $pull: {'cart.items': {productId: prod ...

ajax is providing identical data when called too frequently

Using my barcode scanner triggers the function below, but scanning multiple barcodes quickly results in duplicate data being processed. The issue seems to be related to the async setting - when it's false, the process slows down significantly. Is the ...

Applying styled text to a Node.js chat application

I developed a chat application using node.js which allows users to enter a username and send messages. The messages are displayed in a <ul> format showing "username: message". I was looking for a way to make the username appear bold and in blue color ...

Oops! Looks like there's a problem with the syntax - the import statement can't be

I encountered an error while trying to create Sequelize migrations in my Node.js app (which is set up with Typescript). When running npx sequelize-cli db:migrate, I received an "import method" error, but I'm unable to pinpoint the source of this issue ...

Can nswag (TypeScript) be utilized to automatically generate personalized HTTP Headers?

I utilize the nswag npm package to generate HTTP services, interfaces, and more. A sample TypeScript code for a typical service proxy is shown below: @Injectable() export class TenantsServiceProxy { ... constructor(@Inject(HttpClient) http: HttpClien ...

Transmitting a PHP Bidimensional Array to JavaScript with Ajax

I am looking to send this PHP array to JavaScript using AJAX Here is the array contained in my main.php file: $entries = ldap_get_entries($ldap, $sr); for ($i=0; $i<$entries["count"]; $i++) { if (isset($entries[$i]["cn"][0])) { $ ...

Creating a spherical shape for particles using Three.js

Currently delving into the world of three.js and seeking to morph the example code below to render circular dots instead of square ones. Check out the Codepen example here. A different demonstration named canvas particle random showcases round particles, ...

How can you use Jquery's .data() method to find elements with specific values?

I have a button that generates a new drop pin. The pin is contained within a div, and a hidden form input is also created to store the position of the pin when it's dragged. In my jQuery code for creating these elements, I assign a data attribute call ...

Accessing the property of the scrollbox in Reactjs: How to get the horizontal offset

I am currently working on a scroll view designed as a series of views wrapped horizontally within a container. <div id="scroller" ref="scroller" onClick= {this.onClick.bind(this)} onMouseMove={this._onMouseMove.bind(this)}> {t ...

Troubleshooting: Images not displaying on webpage due to Ajax, JQuery, and JavaScript integration

I'm currently working on building a dynamic photo gallery using Ajax and JQuery in Javascript. I have set up a directory named "images" in Visual Studio Code and it contains my selection of 5 images. However, when I click the "next" and "previous" but ...

Transforming a file into an array using the FS module

I need assistance converting a simple "en.txt" file into an array for NodeJS using FS. "TITLE" => "Amazing title of my page" "COPYRIGHT" => "Copyright my site" "BLABLA" => "A amazing sentence" Any help would be greatly appreciated. Thank ...

Utilizing a variety of textures across various surfaces of a single geometry

I'm new to working with Three.js and I have a question about displaying multiple images over a plane geometry. Here is the scenario: Imagine a simplified case where we have a plane divided into tiles like this: +---+---+---+ | 1 | 2 | 3 | +---+- ...

update the element that acts as the divider in a web address (Angular)

Is it possible to modify the separator character used when obtaining the URL parameters with route.queryParams.subscribe? Currently, Object.keys(params) separates the parameters using "&" as the separator. Is there a way to change this to use a differe ...

Issue with Bootstrap form validation not displaying errors until form submission

I have been working on validating my contact form using Bootstrap 4. Currently, the validation only occurs after submission, but I would like it to highlight errors as soon as incorrect information is entered in a field and the user moves to another field. ...

Tips for updating the DOM within a map function by utilizing the onChange event with a checkbox and react hooks

Initially, I imported a basic "database" object from another file that contains an array of students. I then used map to iterate through the student array and display all the students on the window object. Everything was working fine until I attempted to ...

The database does not get updated by an Ajax request without a page refresh

I'm currently in the process of developing a dashboard system and I've created a ToDo list for it. The main functionality of the system is to allow users to add, delete, and mark tasks as finished or unfinished. I am using codeIgniter for this p ...

Upon initial loading, the width of the Step Line Chart in DevExtreme appears to be incorrect

Is it strange that the initial chart width is set at 400 but changes to 100% when I adjust the window size? If anyone has insight into why this happens, please share! Check out this image for reference ...

Creating a list of font sizes for each <p> tag in my HTML document

I am looking to create an array containing the font sizes of all the p tags in my HTML document. How can I specifically target only the p elements and not their parent elements? ...