What is the best way to dynamically disable choices in mat-select depending on the option chosen?

I was recently working on a project that involved using mat-select elements. In this project, I encountered a specific requirement where I needed to achieve the following two tasks:

  1. When the 'all' option is selected in either of the mat-select elements, all other options should be disabled.
  2. When an option is selected in one mat-select element, that same option should be disabled in the other mat-select element. For reference, here is the stackblitz link to the project

Thank you in advance for any assistance provided!

Answer №1

Include this code snippet in your second option group

<mat-optgroup *ngFor="let set of collectionList" [label]="set.displayName">
  <mat-option *ngFor="let item of set.cards; let index = index"
  [value]="item"
  disabled="{{ selected.includes(item) || selected.includes('all') }}"
  >
    {{ item }}
  </mat-option>
</mat-optgroup>

Answer №2

There is a flaw in the previous solution where selecting all other options will disable both the "all" option as well. To address this issue, you can modify your data structure like this to meet your second requirement.

{
    name: 'Bulbasaur',
    value: 'Bulbasaur',
    selectedByA: false,
    selectedByB: true,
 },
        

Next, in the html section:

[disabled]="anyFunction(index, value)"

Now, let's implement our logic here:

isDisabled(index, value) {
    if (value.name != 'all') {
      if (index === 1) {                              // mat-select-one
        return value.selectedByB || this.allSelected; // returns true if either selected by mat-select-B or all are selected
      } else {                                        // mat-select-two
        return value.selectedByA || this.allSelected; // returns true if either selected by mat-select-A or all are selected
      }
    } else {
      return false; // always return false for Option 'all'
    }

  }

I have made changes to your Stackblitz example.

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

Lists are not limited to only <li> elements and elements that support scripts (<script> and <template>)

While testing my webpage's accessibility in Google Chrome Lighthouse, I encountered the following error. I am aware of the significance of properly structured lists in enhancing webpage accessibility. It is perplexing for me to receive this error desp ...

Error: React-Redux unable to locate Redux context value while utilizing useSelector function

After creating a store and authreducer, everything was working as expected. However, when I added the useSelector in app.js, an error occurred: ERROR Error: could not find react-redux context value; please ensure the component is wrapped in a <Provid ...

employ the value of one array in a different array

Currently, I am working with an array (const second) that is being used in a select element to display numbers as dropdown options {option.target}. My question is: Is there a way to check within this map (that I'm using) if the 'target' from ...

JavaScript - All values stored from the for loop are registering as undefined

Recently delving into the realm of JavaScript programming, I find myself faced with a new challenge. While not my first language, this is one of my initial ventures with it. My current project involves creating a chess program utilizing the HTML5 canvas fe ...

Modify CSS image according to the user interface language in asp.net

Is there a way to dynamically change the image based on different cultures in my ASP.NET webpage? I have successfully been able to switch strings using a resource file, but I am unsure how to handle images. Currently, I have an A tag with a specific clas ...

Issue with the Bootstrap carousel jQuery plugin

Hi everyone, I need some help with creating a multiple items bootstrap carousel. I keep getting an error message that says "#Carousel".carousel is not a function TypeError: "#Carousel".carousel is not a function. Can anyone guide me on how to fix this issu ...

Store the results in the database following the execution of a protractor test

I am completely new to angular protractor testing. I have created some test cases using the protractor framework with jasmine runner BDD style. Within a single test class, I have 10 to 12 specs, each with an expectation. Currently, I am running these tests ...

Eliminate elements from an array using a specific key for filtering

My Array is called MainArray MainArray=[{ {First Name: "First Name"}, {Last Name: "Contact"}, {Last Name: "Contact"} ] I am trying to trim the key-value pair from this array like this: if (key == 'First Name') { del ...

Guide on creating a universal template from a collection of interfaces

Two interfaces, AllTypes type: interface A { // ... } interface B { // ... } type AllTypes = A | B; How can I utilize generics to ensure that a function's argument is an object with either interface A or B? // pseudocode function test<T ...

Guide on incorporating secondary endpoints to develop an API for an Angular library

Challenge: I recently developed a customized UI library using ng-packagr, where I exported unique components along with some model classes. Issue: While the import statement functions correctly for the exported components in my main project, it fails to ...

Troubleshooting the unsuccessful outcome of the node js async.map function

Context I am new to working with Node.js and the async module. I am encountering difficulties with making synchronous calls to my redis database. Objective My ultimate goal is to return a JSON object when the user calls my REST API's GET method. Th ...

When using AngularJS in conjunction with Karma-Jasmine, it is important to note that the functions verifyNoOutstandingExpectation() and verifyNoOutstandingRequest() may not

There is an unresolved HTTP request that needs to be flushed. When I use the following code afterEach(function(){ $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); The code functions correctly and I ...

Angular 2: Export Data to CSV and Download

My backend is built in a Spring Boot application where I am returning a .csv file. @RequestMapping(value = "/downloadCSV") public void downloadCSV(HttpServletResponse response) throws IOException { String csvFileName = "books.csv"; ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

Tips for updating a specific portion of a component in react.js

import React,{useEffect} from 'react'; import CloudTables from '@cloudtables/react'; import { useState } from 'react'; function DataGridTable ({ input1Value, input2Value }) { return ( <div className="con ...

What are the limitations of using a JS file within an Angular application?

I am struggling to integrate some js methods from a file into an angular application. Unfortunately, the browser is unable to recognize the js file. I have tried following the guidelines in this SO post, but the browser still cannot locate the file in the ...

Tips for mocking a module with a slash character in its name?

When it comes to mocking a standard npm project, the process is simple. Just create a __mocks__ folder next to the node_modules folder, then name the file after the package and insert the mock contents. For example: /__mocks__/axios.ts However, I encount ...

Nextjs API call ended without a response being sent

I am currently facing a challenge in my NextJS project as my endpoint API does not support multiple calls, and I am looking to implement a data refresh every 3 minutes from the original source. To achieve this, I have integrated an API in NextJS by creati ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...

What is the best way to extract multiple values from a JavaScript variable and transfer them to Node.js?

Script JavaScript script snippet embedded at the bottom of an HTML file: var savedValues = [] var currentId = document.getElementById("fridgeFreezer").value function handleChange() { // Logic to handle user input changes: var temp = document.ge ...