Tips for displaying an element for each item chosen in a multi-select box

I currently have a situation where I am rendering for every selected element within my multiselect angular material selectbox.

The rendering process functions correctly when I select an element, but the issue arises when I try to deselect one - it just keeps adding instead of removing.

My assumption is that I need to set a property like "deselect" or something similar, but I am not entirely sure. Could someone please assist me with this?

HTML:

<mat-select [formControl]="person" required>
    <mat-option>--</mat-option>
    <mat-option *ngFor="let person of person" [value]="person" (click)="getPerson()">
      {{person.name}}
    </mat-option>
</mat-select>

<div *ngFor="let person of personsArray">
    <div class="card"  >
        <div class="card-body dl-card-body-no-padding-bottom" >  
            //element to render
        </div>
    </div>
 

TS:

getPerson(){
   this.personsArray.push(this.form.controls.person.value)
}

Answer №1

Ensure that the HTML for your mat-select includes the multiple attribute.

Additionally, ensure that you use distinct array names to store items from the source array and the selected array to avoid confusion in the select template.

To pass data into the selection handler, make sure to follow the updated HTML snippet below:

<mat-select [formControl]="person" required multiple>
  <mat-option>--</mat-option>
  <mat-option
    *ngFor="let individual of personsArray"
    [value]="individual"
    (click)="getPerson(individual)"
  >
    {{ individual.name }}
  </mat-option>
</mat-select>

In your component code, define separate arrays for the source array and selected items:

form: any;
person = new FormControl('');
personsArray: Person[] = [
    { name: 'alice' },
    { name: 'dan' },
    { name: 'gary' },
];
selectedPersonsArray: Person[] = [];

constructor() {
    this.form = new FormGroup({
      person: new FormControl(''),
    });
}

The selection handler should handle adding or removing items based on their existence in the select items array:

getPerson(value: Person) {
  console.log('selected person = ' + value.name);
  const person: Person = this.selectedPersonsArray.find(
    (p) => p.name === value.name
  );
  console.log('sel person=' + person?.name);
  if (!person) this.selectedPersonsArray.push(value);
  if (person?.name)
    this.selectedPersonsArray = this.selectedPersonsArray.filter(
      (p) => p.name !== value.name
    );
}

The Person interface defines the structure of the person object as follows:

export interface Person {
    name: string;
}

With these adjustments, your multi-selection dropdown list will properly display selected and un-selected items.

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

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

Guide to creating a Javascript API wrapper

I'm currently working on a React client and I have a question regarding the implementation of a JavaScript wrapper. The APIs I am using return more data than is necessary for the client, so I want to create an index.js file where I can call the API, r ...

Alert: Mouse Exiting Window - Moodle Prompt

I have created an online exam using the Moodle platform, coded in PHP. I am now looking for a way to prevent test-takers from navigating away from the test by implementing a mouseover pop-up. Below is the code I have for triggering an alert pop-up when th ...

End the div element upon completion of the Vimeo video

I am in need of a website that includes an intro video displayed as a full-width div over the background content. To achieve this, I created a Div containing an iframe video from Vimeo along with a button to skip the intro (which closes the div upon clicki ...

What are the steps to update data using Angular?

I am currently working on a project to create a simple webpage that allows users to add values to a database. The database only contains an ID and a value, which should also be displayed on the page. Although my code is functioning correctly and I can suc ...

Scrollbar width does not expand when hovered over

I am having trouble increasing the width of the scrollbar when hovering over it. However, I keep receiving an error in the console stating that 'scrollbar.addEventListener' is not a function. JAVASCRIPT setTimeout(function() { const scrollbar ...

The PointCloud vertices in Three.js consistently provide a position of (0,0,0)

I'm working with a PointCloud named "cloud" that is centered at (0, 0, 0) and consists of approximately 1000 vertices. These vertices' positions are being manipulated by a vertex shader. My goal now is to log the position of each vertex to the co ...

Tips for preventing the ExpressionChangedAfterItHasBeenCheckedError while utilizing [(ngModel)] with a textarea element

I have developed a component that is responsible for managing the details of an object through a form. The object is defined within the app.component.ts: export class AppComponent { selectedItem: Item; } The object is passed into the component using tw ...

execute action once element has finished loading - angular

I am looking for a way to trigger an angular function after a specific element has been displayed on the page. The challenge arises because this element is part of a Single Page Application (SPA) where its display is controlled by a series of events. Tradi ...

Is it possible to display two separate pieces of content in two separate divs simultaneously?

import React from "react"; import ReactDOM from "react-dom"; ReactDOM.render( <span>Is React a JavaScript library for creating user interfaces?</span>, document.getElementById("question1") ) ReactDOM.render( <form class="options"> ...

Tips for testing validation messages in Angular template-driven forms

I have created a simple Angular template-driven form with one required field. An error message is supposed to be shown if the field is not valid, such as when the component is initially loaded and the required field is empty. The code functions correctly i ...

Creating a TypeScript type that supports a flexible number of generic parameters

I am currently working on creating an emit function that has the capability to accept multiple arguments. In addition, TypeScript will validate the 2nd argument and beyond based on the 1st argument (the event). The code provided below is a starting point, ...

The Slice method is malfunctioning after the array has been filtered

I am currently working on creating a news portal app using Next JS, Redux, mongoose, and Express. My Issue is: While I am able to filter specific items from an array successfully, I encounter problems when attempting to display a specific number of items, ...

Preventing users from selecting both future and current dates in a Bootstrap datepicker: A Step-by-Step Guide

Issue Description: I am working on a project using React JS and have implemented the bootstrap datepicker. I have set the input type to "date" for the date of birth field, but I need to restrict users from selecting current or future dates. How can I achie ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

Discovering the most concise string within the array

I've been working on a JavaScript program function that is supposed to return the smallest string in an array, but I keep encountering an error whenever I run it. Below is the code I have written: function findShortestWordAmongMixedElements(arr) { ...

Press the delete button located on the child component to trigger an action in the

I'm in the process of developing a simple to-do application from scratch in order to familiarize myself with ReactJS. One challenge I'm facing is implementing the delete functionality for todos, as I want to keep the button within the Todo compon ...

Unable to Retrieve Data When Using ASP.NET MVC with Angular

Currently, I am in the process of learning Angular and have managed to grasp the basics needed to get started. In my ASP.NET Core project, I successfully installed Angular without using the default template in Visual Studio 2017 and was able to run the pro ...

Implementing an object as a filter in an NG-repeat function

I've created multiple select dropdowns that are populated from a JSON file containing categories. My goal is to use the selections made by users in the dropdowns to filter a list of apps generated using ng-repeat. In my Plunker example http://plnkr. ...

What sets apart an object within the scalajs scope from the exact same object within the js.global scope?

Attempting to create a basic example for rendering a cube using the THREEJS library. package three import org.scalajs.dom import scala.scalajs.js import scala.scalajs.js.Dynamic._ import scala.scalajs.js.annotation.JSName ... object ThreeExample { d ...