What is the best way to fill an array with specific dropdown values in Angular?

My task is to dynamically populate an array with all selected values from a mat-select dropdown in Angular. The end goal is to generate an input field for each selected value, similar to the example shown below:

Image

I've been contemplating calling a method every time a value is selected, but I'm uncertain about the next steps... Here's what I have so far:

MyComponent.component.html

<mat-form-field>
  <mat-select placeholder="Products" [formControl]="products" multiple>
    <mat-option *ngFor="let product of productsList">{{ product }}</mat-option>
  </mat-select>
</mat-form-field>

MyComponent.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'm-mycomponent',
  templateUrl: './mycomponent.component.html',
  styleUrls: ['./mycomponent.component.scss']
})
export class MyComponent implements OnInit {

  products = new FormControl();
  productsList = ['Prod1', 'Prod2', 'Prod3', 'Prod4', 'Prod5', 'Prod6'];
  productsToReturn = [];

  constructor() { }

  ngOnInit() {
  }

  fillProductsToReturn(product){
    if(!this.productsToReturn.includes(product)){
      this.productsToReturn.push(product);
    }
  }
}

I'm looking for guidance on how to trigger a method within the HTML file to update the productsToReturn array. Any help would be greatly appreciated!

Thank you!

Answer №1

It's important to clarify when you need to access the selected objects.

If you require access upon form submission, such as when a button is clicked, you can simply use this.products.value to retrieve the selected options.

Alternatively, if you need access at the moment of selection, you can listen for the selectionChange() event.

<mat-select placeholder="Products" [formControl]="products" multiple (selectionChange)="onSelectionChange($event) >

In your TypeScript file, you can then access the selected options like this:

onSelectionChange(e){
    console.log(e.value); //or
    console.log(this.toppings.value);
}

Answer №2

Instead of manually handling it, you can easily bind the value property of the mat-option to the current product string. This will automatically update your FormControl with the selected options.

Here's how you can set it up in your template:

<mat-form-field>
  <mat-select placeholder="Products" [formControl]="products" multiple>
    <mat-option *ngFor="let product of productsList" [value]="product">{{ product }}</mat-option>
  </mat-select>
</mat-form-field>

In your component, you can retrieve the selected options by accessing this.products.value.

If you need a working example, check out this minimal stackblitz demo. The selected values will be displayed next to the mat-select.

Answer №3

I successfully resolved my issue... After consulting with j4rey and implementing their suggestions, I made the necessary modifications.

Here is an excerpt from MyComponent.component.html:

<mat-form-field>
  <mat-select placeholder="Products" [formControl]="products" multiple>
    <mat-option *ngFor="let product of productsList" [value]="product" (onSelectionChange)="onSelectionChange(product)">{{ product }}</mat-option>
  </mat-select>
</mat-form-field>

<div class="row" *ngFor="let product of productsToReturn">
  <div class="col-4">
    <mat-form-field>
      <input matInput disabled="disabled" [value]="product">
    </mat-form-field>
  </div>
  <div class="col-2">
    <mat-form-field class="prod-qty">
      <input matInput step="1" value="1" min="1" type="number">
    </mat-form-field>
  </div>
</div>

This snippet is taken from MyComponent.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'm-mycomponent',
  templateUrl: './mycomponent.component.html',
  styleUrls: ['./mycomponent.component.scss']
})
export class MyComponent implements OnInit {

  products = new FormControl();
  productsList = ['Prod1', 'Prod2', 'Prod3', 'Prod4', 'Prod5', 'Prod6'];
  productsToReturn = [];

  constructor() { }

  ngOnInit() { }

  onSelectionChange(product: string) {

    if (!this.productsToReturn.includes(product)) {
      this.productsToReturn.push(product);
    } else {
      let index = this.productsToReturn.indexOf(product);
      this.productsToReturn.splice(index, 1);
    }
  }
}

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

Ensuring the protection of API requests in a Phonegap/Cordova application

As I work on developing a Phonegap application that requests data from my server via API, I want to ensure that only authorized users are able to access this data. To achieve this, I have implemented HTTP basic authentication. This method involves includi ...

Is there a way to implement absolute imports in both Storybook and Next.js?

Within my .storybook/main.js file, I've included the following webpack configuration: webpackFinal: async (config) => { config.resolve.modules = [ ...(config.resolve.modules || []), path.resolve(__dirname), ]; return ...

Encountering issues while trying to establish a connection to MongoDB through JavaScript

I have developed a code for seamlessly integrating various social networking logins with nodejs. Below is my server.js file: // include the necessary tools var express = require('express'); var app = express(); var port = process.env ...

What causes the low Performance score of a default NextJS Application with no content?

Just started experimenting with my initial Next.js project. Upon generating a new project using create-next-app, I decided to test its performance with the web application 'Lighthouse'. Surprisingly, although most other metrics scored above 90, ...

Struggling to extract specific data from a table using angular.js

My table includes Roman numerals (i.e. I, II, III, ......VIII) for filtering using Angular.js. However, I am facing an issue where the filtration process works for some values but not for others. Please review my code below: subject.html: <table cl ...

How can I make text automatically resize within a fixed DIV based on the length of the text?

What's the best way to handle text in a fixed width and height DIV that can vary in length? I'm okay with reducing the size of the text when it overflows, but how can I make that happen? Any advice would be appreciated. Thanks! ...

Importing modules from another module in Node.js

I'm currently working on a nodejs app that consists of two files, index.js and ping.js. The main functionality is in index.js which handles routing and other tasks, while ping.js utilizes phantomJS. In my index.js file, I have the following line of co ...

Repeated data submissions occur when using a modal form

I have a dataTable List with buttons attached to each row as shown below: https://i.sstatic.net/9vujB.png When a button is clicked, a Modal form is displayed. The modal is uniquely generated for each row in the table and has a different ID. https://i.ss ...

No children were located within the div element

Presently, I am attempting to disable an image for the initial element in each faqs div class in HTML. To achieve this, I am aiming to target the parent element of faqs and then navigate downwards to locate the initial list element using the following Java ...

The ios browser environment is unable to retrieve the value during vuejs development

When using vuejs components to create a countdown component, everything seems normal in the pc and Android environments. However, in the iOS environment, there seems to be an issue with obtaining the real count calculation as it returns NaN. <templ ...

The Twitch stream is currently live, but the user is not actively online

I've developed a NODE JS bot that keeps track of Twitch users and sends a message to the "GroupMe" app whenever a user goes online. Although it generally works well, there are instances when the bot mistakenly indicates that a user is online when they ...

Angular: Trigger service worker to handle push notification event from service

Is it possible to call the service worker push event from a custom service in Angular? I implemented this code in my service, and it works on desktop and android, but not on iPhone. navigator.serviceWorker.register('sw.js'); Notification.request ...

Changing the color of a div's text based on its content with CSS

I am facing a challenge in styling the text inside a “div” element using a Javascript function. Initially, when the page loads, these “divs” contain no value. The values of the "divs" will change between "Open" and "Closed" twice a day when the Jav ...

Intercepting and handling errors thrown by a Node module

I have been encountering an issue with a module that throws errors without them being returned as part of the callback, causing the program to stop when an error is thrown. The code snippet I am using looks like this: co(function*(){ try{ for (let ...

After completing the payment, Paypal Express checkout causes the page to refresh

I have integrated an Express checkout button into my webpage and configured the server-side process with client code: <script src="https://www.paypalobjects.com/api/checkout.js"></script> <script> var CREATE_PAYMENT_URL = "<create ...

developing a multimedia player using HTML5

I'm attempting to create a dynamic video "collage" that showcases videos with different aspect ratios in a flexible grid layout. Each row should have videos of the same height, while filling up the horizontal space within a container. With known widt ...

Encountering an uncaught syntax error with Jquery on the production environment, although it works fine on the test file. Also, facing issues with

$("#themeSelector").click(function(e) { themes = { 'Theme1': 'https://bootswatch.com/4/theme1/bootstrap.min.css', 'Theme2': 'https://bootswatch.com/4/theme2/bootstrap.min.css', 'Theme3': &apos ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

The default selection in res.format is not being properly recognized

When I make a request with the accept header set as "application/json, text/javascript, */*; q=0.01", the response is always in HTML format instead of the default format specified. It seems like something is missing here. Given that the header does not spe ...

Verification checkbox in Html5 is mandatory

I have created an input checkbox that contains array values, resulting in multiple rows being generated in a table. However, the issue I am facing is that all checkboxes need to be checked in order to submit the form. This means I cannot submit the form un ...