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

Prevent the parent component's ripple effect from being activated by the child component

If I have a simple code snippet like the following: <ListItem button={true} > <Typography variant='caption' color='primary'> {value} </Typography> <Button onClick={foo} > Button ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

Ember.js: Storing function prototypes as objects

My interface consists of four vertical panels: The first panel displays the menu for selecting data The second panel allows you to choose a filter from a list The third panel shows the results based on the selected filter The fourth panel displays detail ...

Post-Angular migration (going from version 12 to 14), there are still lingering security risks associated with the "d3-color vulnerable to ReDoS" issue

Following the migration to Angular 14, I made sure to update my "@swimlane/ngx-charts" version to "20.1.2" and the "d3" version to "7.8.4". However, even after running the npm install command, I am still encountering 5 high severity vulnerabilities in my p ...

Steps for transforming an Array of hierarchical data into the correct JSON format for D3 Tree Region visualization

I am struggling with converting an array of hierarchy data into the correct Object format. Here is what I am trying to convert: [ {"PARENT_ID": 0,"CHILD_ID": 1,"NAME": "Quality","LEVEL_A": 0}, {&qu ...

Jquery Droppable issue arising with dynamically added DIVs

I am facing a similar issue as described in this question and this one I am trying to implement drag-and-drop and resize functionality. It is working fine for static elements, but I encounter issues when adding dynamic divs. The resize property works prop ...

invalid audio element

I'm currently working on building an audio player with a visualizer feature. However, when I try to initiate the audio player by clicking on the input button, my debug console keeps showing this error message: Uncaught (in promise) DOMException: Fa ...

Encountering an issue with Next.js React SSR using styled-jsx: unable to access the 'state' property as

I've come across a problem that I can't seem to figure out. Despite my attempts to search for a solution here, I haven't been able to help myself. I'm new to javascript and react, so please bear with me. Issue: I'm using React (1 ...

Understanding how to utilize jQuery or prototype to interpret onclick event containing "setLocation(...)" can enhance the functionality

I am dealing with a specific tag: <button onclick="setLocation('http://mysite.com/checkout/cart/add/product/17/')" /> My goal is to trigger an ajax request when the button is clicked. I want to extract the URL segment "product/17" and app ...

What is the process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

What is the best way to showcase several images using Sweet Alert 2?

In the process of developing my Angular 2 application, I have incorporated sweet alert 2 into certain sections. I am looking to showcase multiple images (a minimum of two) at the same time in the pop-up. Does anyone have any suggestions on how to achieve ...

JS Executing functions in a pop-up window

Recently, I have been immersing myself in learning JS and experimenting with webpage interactions. It started with scraping data, but now I am also venturing into performing actions on specific webpages. For example, there is a webpage that features a butt ...

Is it possible for node.js to execute promises without needing to await their fulfillment?

When I visit the Discord tag, I enjoy solving questions that come my way. While I am quite proficient in Python, my skills in Javascript are just about average. However, I do try my hand at it from time to time. The Discord.py library consists of several ...

Is it possible to refresh the chat-box using PHP?

I recently created a chat box application using PHP, but I'm facing an issue with its automatic reload functionality. Is there a way to implement auto-reload in PHP itself, or would it be better to restructure the system to utilize AJAX? Additionally, ...

Learn how to efficiently pass multiple props using a loop in Vue

I am dealing with an object that has multiple properties. Typically, I know which props I want to pass to my component and do it like this: <component :prop1="object.prop1" :prop2="object.prop2" :prop3="object.prop3" /> However, I want to pass the ...

Unable to locate the required conditional template for the 'mdRadioButton' directive due to the absence of the 'mdRadioGroup' controller

I am currently working on developing a custom directive that will help me display questions within a survey. Given the multiple types of questions I have, I decided to create a single directive and dynamically change its template based on the type of quest ...

various locations within a hexagonal zone or figure

In my project, I am working with a simple hexagonal grid. My goal is to select a group of hexagons and fill them with random points. Here is the step-by-step process of generating these points: I start by selecting hexagons using a list of hex coordinat ...

Passing a Javascript variable to the NAME attribute of an HTML <a href> tag: Steps to do it efficiently

I need assistance with passing a JavaScript variable to the NAME attribute of an HTML tag. Let's consider this script example: <script> var name = "Click here!"; </script> My goal is to pass the variable to some code in order for <a ...

Adding input values to a jQuery Ajax POST request

I am currently attempting to send form values to a remote API using AJAX. The necessary information I require from the HTML form element includes the author, string, false, and true. At the moment, I have hard-coded some values but... function sendData ...