Unable to add chosen elements to array - Angular material mat select allowing multiple selections

Can anyone assist me in figuring out what I am doing wrong when attempting to push data to an empty array?

I am trying to only add selected values (i.e. those with checked as true), but I can't seem to get inside the loop

This is the current condition:

const vals = [];
    if (e && e.source.selected.length > 0) {
      console.log('selected values', e.source.selected);
      const sel = e.source.selected;
      sel.forEach((e: any) => {
        if (sel._selected) {
          vals.push(e);
          console.log('EE', e);
        }
      });
    }

Check out the demo on StackBlitz

Expected output:

selectedList : [
{ id: '0' }, { id: '1' }, { id: '2' }
]

Purpose:

Attempting to bind the same data in edit mode within a form

Answer №1

Forget about using your function altogether. Just delete it and use this instead:

console.log(e.source.value);

This line of code already contains all the selected values!

Whenever you update, the array will automatically reflect only the selected values.

If you want to change it to look like this:

expected:

selectedList : [ { id: '0' }, { id: '1' }, { id: '2' } ]

just use this piece of code:

let selectedList = e.source.value.map((elem: number) => ({ id: elem }));
console.log(selectedList);

Answer №2

Give this a try!

onSelectingToppings(e: any) {

const toppings:any[] = [];
if (e && e.source.selected.length > 0) {
  // console.log('selected values', e.source.selected);
  const selectedToppings = e.source.selected;
  selectedToppings.forEach((item: any) => {
    if (item._selected) {
      toppings.push(item);
    }
  });
  console.log(toppings.length)
}
}

Answer №3

Seems like there may be an issue with your if statement, the revised version should look like this:

const values = [];
if (element && element.source.choices.length > 0) {
  console.log('selected choices', element.source.selected);
  const selection = element.source.selected;
  selection.forEach((item: any) => {
    if (item.selected) {
      values.push({"id": item.value});
      console.log('Selected ID', {"id": item.value});
    }
  });
}

If you are experimenting with something different, consider adding a console log before your if statement within the loop to troubleshoot the issue.

Answer №4

To prevent errors when no value is selected or the page is initialized, optional chaining has been added to the code. Now, sel holds the array of selected values without causing any issues. Check out the updated code below:

    if (e && e.source?.selected?.length > 0) {
      console.log('selected values', e);
      const sel = e.source.selected;
      sel?.value?.forEach((e: any) => {
          vals.push(e);
          console.log('EE', e);
    
      });
    }

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

Nodejs asynchronous tasks are not functioning correctly with SetInterval

I'm a newcomer to the world of Node.js. I've set up a simple asynchronous task that needs to run every 10 minutes. The setInterval function should trigger at regular intervals as specified, updating the value for the variable api key. I can' ...

Cypress, encountering issues with If/Else or Switch Case implementations

My current challenge involves adding else if / switch case in my test. The issue I am facing is that when the initial 'if' condition fails, it does not go into the else if statement. This problem persists in both else if statements and switch cas ...

Incorporating a stationary navigation bar alongside a parallax scrolling layout

After spending the entire night trying to figure this out, I have had zero success so far. I decided to tackle this issue with javascript since my attempts with CSS have been completely fruitless. This is a demonstration of the parallax scrolling webpage. ...

Avoid losing any entered form information when leaving the page

As I work on creating a datagrid with hundreds of rows, each row features a checkbox that allows users to select items from the grid. I've noticed that users might spend considerable time filtering and searching through the grid, ticking checkboxes a ...

Having Trouble with Angular2: Nesting a Child Component?

Working with angular 2 has been a fun experience for me over the past few days. I've been attempting to insert a child selector into a parent template, but it seems more challenging than I expected. Every time I try, I encounter the following error: ...

Retaining original input value even when validation is applied with input type="number"

Encountering an unusual scenario while using angularJs and input type="number". It seems that if the initial value of an input falls outside the specified min and max range, the value gets wiped out. To better visualize the issue, I created a fiddle - htt ...

Maintain the spacing of an element when utilizing *ngFor

Using Angular.js and *ngFor to loop over an array and display the values. The goal is to preserve the spaces of elements in the array: string arr1 = [" Welcome Angular ", "Line1", "Line2", " Done "] The ...

Center the span in CSS by setting its position to absolute

I am trying to create a span element positioned as absolute inside a div. The div has top and left values set. When the user inputs text, the span expands with the given text towards the right to contain it. However, I would like it to grow symmetrically o ...

refresh Laravel 5.1 webpage content seamlessly without page reloading

Is there a way to update page content in Laravel 5.1 every second without reloading the page for all users? Here is my current view: I'm trying to refresh data without reloading the page using a foreach loop, but I'm not sure how to accomplish ...

refreshing the webpage with information from an API request

I am completely new to web development, so please bear with me. I am attempting to make a simple API call: const getWorldTotal = async () => { const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/cov ...

The code compilation of Typescript in a Dockerfile is not functioning as expected due to the error "Name 'process' cannot be found."

Here's the Dockerfile I'm working with: FROM node:latest WORKDIR /usr/src/app ENV NODE_ENV=production COPY package*.json . RUN npm install && npm i -g typescript COPY . . RUN tsc CMD [ "node", "./dist/index.js&qu ...

Retrieve the identification number from the code snippet containing the "append(<tr><td="ID">..." template

I have a table that I'm populating with data from a firebase database using the append() function. $("#table_body").append("<tr><td>" + name + "</td>" + "<td>" + brand + "</td>" + ...

Making a POST request using axios in a MERNStack application

After successfully using the express router to add articles with Postman, I encountered an issue when trying to send article information through Axios to MongoDB. Despite no errors appearing in the console, there was a message stating "SharedArrayBuffer ...

Having trouble storing data accurately in local storage using React

I implemented a combination of useContext and useEffect to store useContext data in local storage, but I am facing challenges due to conditional rendering. The scenario involves displaying a sign-in button when the user is not logged in and a log-out butto ...

What factors influence the speed of an Ajax request?

It is common knowledge that the amount of data transmitted to the server, as well as the volume of information returned in a call can greatly affect its speed. However, what I am curious about is whether the following factors might also impact the transmi ...

Initiating a conversation using a greeting in the Javascript bot framework

I am looking to initiate a multi-level, multiple choice dialog from the welcome message in the Bot Framework SDK using JavaScript. I have a main dialog (finalAnswerDialog) that utilizes LUIS for predicting intents, and a multi-level, multiple choice menu d ...

Utilizing variable index to access nested objects

When my Ajax request returns a response, the data takes the form of an object shown below: How can I access the value? Keep in mind that idVariable is a variable. data.test1.idVariable.test2.value The result of the code above is: undefined. ...

Tips for adding spacing when the sidebar collapses and expands in a React application

I am attempting to achieve a layout where the body adjusts its space when the sidebar collapses and expands. Here is how it appears when the sidebar expands: see expanded sidebar here And this is how it looks when the sidebar collapses: see collapsed s ...

The ElementRef was modified following the activation of a click event

Let me explain my current situation: I am working with 3 components: MainComponent, ComponentA, and ComponentB. MainComponent dynamically loads ComponentA. ComponentA contains a button that, when clicked, calls MainComponent.addComponent(ComponentB). exp ...

unable to retrieve the city name through geographical location information

I am currently using the following code snippet to retrieve the country and city names: <?php $user_ip= getenv('REMOTE_ADDR'); $geo= unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip")); $city= $geo["ge ...