select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list

Click here for image illustration

When the user selects in, only records with type in should be displayed

Another image reference is available here

Despite my efforts, I haven't been able to achieve this functionality. However, during my research, I stumbled upon this helpful page.

Upon selecting in, my HTML table appears empty without fetching any records. Can you help identify the issue?

service.ts

@Injectable({
    providedIn: 'root'
})
export class CorporateActionService {

    startDate = new Date("");

    prea = [{
            num: "758-1184511-34",
            svm: "000902988",
            type: "in",
            quantity: "12,00",
            isin: "BE0003470755",
            title: "SOLVAY BE",
        },
        {
            num: "758-1184511-34",
            svm: "000902987",
            type: "out",
            quantity: "11,25",
            isin: "BE0152676954",
            title: "AXA B FD EQUITY BELGIUM",
        },

    ]

    dataList = [{
            code: 1,
            name: "in"
        },
        {
            code: 2,
            name: "out"
        },
    ]

    constructor() {}
}

component.ts

export class CorporateActionComponent implements OnInit {

    prea: any;
    dataList: any;
    brandName = {};


    constructor(private service: CorporateActionService) {}

    ngOnInit(): void {
        this.prea = this.service.prea;
        this.dataList = this.service.dataList;
        this.brandName = this.dataList.brandName;
    }

    public selectedBrand: any;
    public valueSelected() {
        this.prea = this.service.prea.filter(
            item => item.num === this.selectedBrand
        );
    }

}

component.html

<div class="home-content container ">
   <h1 class="text-center pt-5 pb-3">Corporate Action</h1>
   <div class="row pt-3 container">
      <div class="card" style="width: 100%;">
         <div class="card-body">
            <div class="text-end">
               <select [(ngModel)]="selectedBrand" (change)="valueSelected()">
               <option>Select</option>
               <option *ngFor="let item of dataList;let i = index" value="{{item.code}}" [selected]="i == 0">
               {{item.name}}
               </option>
               </select>
            </div>
            <table class="table table-striped table-hover">
               <thead class="thead-light">
                  <tr class="text-center">
                     <th scope="col">Client</th>
                     <th scope="col">N° de préavis</th>
                     <th scope="col">Type</th>
                     <th scope="col">Quantité</th>
                     <th scope="col">ISIN</th>
                     <th scope="col">Titre</th>
                  </tr>
               </thead>
               <tbody>
                  <tr *ngFor="let line of prea">
                     <td scope="row" class="text-center">{{ line.num }}</td>
                     <td scope="row" class="text-center">{{ line.svm }}</td>
                     <td scope="row" class="text-center">{{ line.type }}</td>
                     <td scope="row" class="text-center">{{ line.quantity }}</td>
                     <td scope="row" class="text-center">{{ line.isin }}</td>
                     <td scope="row" class="text-center">{{ line.title }}</td>
                  </tr>
               </tbody>
            </table>
         </div>
      </div>
   </div>
</div>

Here is a link to test the functionality.

Answer №1

There are a couple of things you can do to improve your code:

First, update the value of the options to use item.name as the identifier.

<option *ngFor="let item of dataList; let i = index" value="{{item.name}}" [selected]="i == 0">

Secondly, make sure to filter the array by the type, as that is where your in and out properties are located.

public valueSelected() {
    this.prea = this.service.prea.filter(
      (item) => item.type === this.selectedBrand
    );
}

Check out the updated code here.

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

The ideal way to efficiently await retrieved data in vue.js to ensure smooth integration in another function

Is there a way to properly handle the successful fetch event before executing the loadMarkers() method? I keep encountering an error because monitorsData.monitors is undefined. I attempted using await with fetch but I'm unsure of the correct usage. ...

Acquire data from an array of objects using JavaScript

I've written some code where I'm attempting to display certain values in HTML. Specifically, I am looking to extract the values from the "current" object: ("dt":1643884851, "temp":8.11, "description":"few clouds", and "icon":"02d") In addition, ...

Unable to import CSV file

I'm currently in the process of developing a CSV editor that involves importing a CSV file and converting it into HTML tables. Below is the code I have been working on: <html> <head> <title></title> </head> <body& ...

Error: The componentwillmount function has encountered an issue. Actions must be in the form of plain objects. For asynchronous actions, consider

Currently, I am setting up a feature to retrieve all images based on their type using redux-saga. There are two types available: kristik and motif. While implementing the kristik type, everything works smoothly and I receive successful responses. However, ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

Managing State in React using Maps

As someone who is new to coding, I am currently facing an issue and seeking help to resolve it. I am using axios to retrieve a JSON file and store it in a state utilizing Redux for form population. I am then utilizing .map() to break down the array and dis ...

What is the best way to modify specific data retrieved from an API using Angular?

After successfully listing some data from an API using ngFor, I am facing an issue with editing the data. Whenever I click the edit button, it edits the entire data instead of just the specific row. Below is the code snippet for reference: HTML <table ...

Guide to connecting data from the backend to the frontend in the select option feature using Angular 9

I have a backend system where I store a number representing a selected object, which I am trying to display in a select option using Angular. Currently, the select option only displays a list of items that I have predefined in my TypeScript code using enu ...

Angular auto suggest feature

I am working with a dropdown in Angular that contains JSON data. The data is stored in a List named options and I need to display the name field in the dropdown list. My current task involves implementing an autocomplete search feature for this dropdown. ...

Uh oh! There seems to be an issue with the ClerkJS frontendAPI option. Visit the homepage at https://dashboard.clerk.dev to retrieve your unique Frontend API value

Despite inputting the correct Clerk API keys, I'm encountering issues with the functionality of the ClerkJS API. I anticipate that the application should enable me to utilize the ClerkJS API for user authentication without any problems. ...

What is the most effective method for managing the onSelect data within the select tag in Angular's reactive form functionality?

Can someone please advise on the best approach to handling this scenario? I have a form with multiple fields, including a select tag. <form [formGroup]="myForm"> <select formControlName="" > <option *ngFor="let c of countries" value ...

Retrieve the height of a div element in an AngularJS framework, and assign this value to a corresponding attribute of another element

Is it possible to retrieve the height of an element using AngularJS and assign it to another div's attribute? In my Bootstrap website, I have a fixed sidebar that needs to stop before reaching the footer. To achieve this, I currently have to manually ...

Features of ES2015's [[class]] attribute

I've been developing a basic clone function var shallowCopy = function (value) { // In ES2017, we could also use // return Object.create(Object.getPrototypeOf(value), Object.getOwnPropertyDescriptors(value)); let propDescriptors = {}; for (le ...

Caching of audio files in React streaming is enabled

My dilemma lies in the fact that despite creating a new file in the back-end, the <PlaySound /> component continues to play the old sound file rather than the updated one. Although the sound file maintains the same name and path, its content differs. ...

Learning how to effectively utilize the tap and map functions in Angular

How can I redirect to a URL received from the backend in my Angular project? public createPaymentMethod(paymentMethodDto: any): Observable<any> { return this.http.post<any>(ConfigService.Configuration.apiUrl + `/payments`, paymentMetho ...

Limiting the ability to pan to a single globe within the Google Maps API

I need help with restricting panning on a Google Maps API map to just one globe. By default, the map allows continuous panning east/west, causing it to repeat endlessly. I found a solution by henningj in response to this question var allowedBounds = new g ...

Creating an asynchronous function in Node.js that returns a promise, but experiencing unexpected behavior when using console.log to display the result

Recently, I created a simple and compact API that determines the gender of a person. It functions by sending a get-request to a specific page which responds with a JSON object. This snippet illustrates how my module works: 'use strict'; const ht ...

Introducing a new element in TypeScript using a separate method with parameters

Currently, I am attempting to create a method that will allow me to add an element to my array. Despite being new to typescript, I have been struggling to determine what needs to go into the addNewProduct function. While seeking help, I came across the p ...

Is it possible to modify the default behavior of a sensitive region within a button?

I created a calculator application in React and overall, it's working fine, however... I've noticed that when I hold a click longer, it only registers as a click if the mouse was pressed down and released on the button itself. Although I unders ...

Can conditional content projection (transclusion) be achieved in Angular 2+?

How can I set default content that will only display if content is not transcluded? Consider the following component template: <article> <header> <ng-content select="[header]"></ng-content> </header> < ...