Concealing Dropdown Box Information Based on a Customized List in Angular

Is there a way to remove an item from a dropdown list once it has been selected? For example, if I have a dropdown box with options 'Dog', 'Lion', and 'Cat', how can I make it so that once I select 'Dog', it will no longer show in the dropdown list? Is this achievable?

Here is the HTML code:

<mat-form-field class="full-width" floatLabel="always" appearance="outline">
  <mat-label>Choose Animal</mat-label>
  <mat-select formControlName="animal">
    <mat-option *ngFor="let items of animal" [value]="items.id">
      {{items.animal}}
    </mat-option>
  </mat-select>
</mat-form-field>

And here is the TS code:

ngOninit() {
  this.getList()
}

getList() {
  this.animalSVC.getListOfAnimal().subscribe((response: AnimalDTO) => {
    this.animalObj = response;
    this.animalDS = this.animalObj.items
  })
}

So, for example, if I select 'Lion' from the list, it should not be available for selection again in the dropdown box.

Answer №1

If you are dealing with a single selection, you can utilize the following code:

  <mat-option *ngFor="let food of foods"
    [hidden]="food.value==form.get('food')?.value"
    [value]="food.value"
  >
    {{food.viewValue}}
  </mat-option>

You will also need to add the corresponding .css styles:

  mat-option[hidden]{
    display:none
  }

However, if the selection allows for multiple choices, you need to provide users with the option to deselect items. This can be achieved by monitoring the user's selection status:

To handle this functionality, we create a variable that updates based on the mat-select's state changes and the deselection of options:

  oldValue:any[]=[]

  <mat-select formControlName="foodMultiple" multiple 
     (openedChange)="oldValue=form.get('foodMultiple')?.value||[]"
     >
    <mat-option #option *ngFor="let food of foods"
      (onSelectionChange)="!option.selected && unSelect(option.value)"
      [hidden]="(form.get('foodMultiple')?.value||[]).indexOf(food.value)>=0 
                && oldValue.indexOf(food.value)<0"
      [value]="food.value"
    >
      {{food.viewValue}}
    </mat-option>
  </mat-select>

We employ a template reference variable, #option, to determine the selection status through option.selected and pass this information to the unSelect function:

The syntax (event)="condition && function()" ensures that the function is only executed if the specified condition is met.

  unSelect(value:string)
  {
      this.oldValue=this.oldValue.filter(x=>x!=value)
  }

By implementing this, deselected options will be removed from the list upon unselection.

Additional Note: If you prefer, you can skip checking for deselected options, but they will remain visible if reselected.

Additional Note 2: Alternatively, you can handle visibility by adding a class dynamically using [class.nodisplay]=... and corresponding CSS mat-option.nodisplay rules.

For a demonstration, you can refer to this stackblitz example

Answer №2

To start, declare a global variable like animalSelectedId: number = null. Next, create a function that will be triggered on changes to store the selected animal ID. When looping through the array of animals, only display the items that do not match the animalSelectedId.

 <mat-form-field class="full-width" floatLabel="always" appearance="outline">
   <mat-label>Choose Animal</mat-label>
      <mat-select formControlName="animal" (selectionChange)="onChange($event)">
         <mat-option *ngFor="let items of animal" [value]="items.id">
            <div *ngIf="items.id !== animalSelectedId">
              {{items.animal}}
            </div>
         </mat-option>
      </mat-select>
 </mat-form-field>
animalSelectedId: number = null

public onChange(e: {value: number}): void {
  animalSelectedId = e.value;
}

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

Performing unit testing on a Vue component that relies on external dependencies

Currently, I am in the process of testing my SiWizard component, which relies on external dependencies from the syncfusion library. The component imports various modules from this library. SiWizard.vue Imports import SiFooter from "@/components/subCompon ...

Exploring the nuances of checking lists in TypeScript

In the following list: empList = ['one','two','finish','one','three'] I am required to evaluate conditions based on empList: Condition 1: If 'two' appears before 'finish', set this ...

Tips for incorporating multiple services within a single Angular component

Issue found in src/app/header1/header1.component.ts:3:30 - TypeScript error TS2306: The file 'F:/Angular-projects/lawyer-listing/src/app/services/state.service.ts' is not recognized as a module. 3 import { StateService } from '../services/st ...

Error: Unable to access the property of an undefined variable in Angular 4

Here is what I currently have in my code: <p *ngIf="model.something.satisfy"> Yes </p> <p *ngIf="!model.something.satisfy"> {{model.something.comments}} </p> The issue arises in the second line with the error message "Type ...

Observable not triggering Subject.next() as expected

service.ts constructor() { this.cartUpdate = new BehaviorSubject<Array<AppCartItem>>([]); // this.cartUpdate.subscribe((items) => { // #### 1 // console.log('Service Items : ', items); // }); } add(item) : Obser ...

Using Angular2 Pipes to display raw HTML content

I am currently working on developing a custom pipe in Angular2 that is capable of outputting raw HTML. My goal is to take input with newlines and convert them into HTML line breaks. Can anyone guide me on how to display raw HTML from an Angular2 pipe? Bel ...

Conditional Dependencies

I'm trying to inject a dependency using @Inject() and I want it to be optional. However, the @Optional() tag doesn't seem to work with this particular type of dependency. According to documentation, the syntax for an optional injection with @Inje ...

I'm encountering difficulty trying to set up sweetalert2 in Angular

Please provide an image description I'm facing a problem and I need assistance. Despite following various installation guides, I have been unable to find a resolution. Please provide an image description ...

Utilizing the Double Mapping Feature in React with Typescript

It seems I might be overlooking something, can someone guide me on how to properly double map in this scenario? I'm encountering an error on the second map: Property 'map' does not exist on type '{ departure: { code: string; name: strin ...

Dynamic Angular routes with varying numbers of parameters

I am working on developing an application where I need to associate TreeList navigation with routes. Consider the file structure in the explore section: - desktop - file1.txt - pictures - wallpaper - my-selfie.png - file2.txt - file4. ...

Array[object..] logical operators

I am currently working with Boolean and logical operators using code like this: Just so you know, I want to convert object values and logic into an array to perform logical operations. For example: object1.logic object.operators object2.logic as either tr ...

Using {children} in NextJS & Typescript for layout components

I am looking to develop a component for my primary admin interface which will act as a wrapper for the individual screens. Here is the JavaScript code I have: import Header from '../Header' function TopNavbarLayout({ children }) { return ...

Transmit live video feed captured by getUserMedia to a Node.js server and then forward it to the Google Cloud Platform speech API

I am currently involved in a project that requires the use of the google-cloud-platform speech API. To achieve this, I am utilizing getUserMedia to acquire the MediaStream. However, I am unsure about what data I should be sending from it to the BackEnd. O ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Is it possible for me to employ T extends Contravariant<any> to effectively restrict a generic type to a union of Contravariants

Let's begin by clarifying some terms: type Contravariant<T> = (t: T) => void; declare let cNum: Contravariant<number>; declare let cStr: Contravariant<string>; Now, suppose I wish to create a function that accepts an array of the ...

Implementing automatic selection for MUI toggle buttons with dynamic data

By default, I needed to set the first toggle button as selected import * as React from "react"; import { Typography, ToggleButton, ToggleButtonGroup } from "@mui/material"; export default function ToggleButtons() { const dat ...

A specialized <T> interface, now enhanced with additional functionalities

Looking to create a generic type (with parameter T) that exhibits the following behavior: If K represents a key of T, allow the value type to be either T[K] | ((params?: Partial<T>) => string) If K is not a key of T, allow the value type to be ( ...

Upgrading Angular causes issues with fileReplacements not functioning properly for assets

Since upgrading Angular, I have encountered an issue where fileReplacements no longer work with assets. Here is the code snippet that I am using: "fileReplacements": [ { "replace": "src/assets/scss/x.scss", ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

Enhance your Next.js routing by appending to a slug/url using the <Link> component

In my Next.js project, I have organized my files in a folder-based structure like this: /dashboard/[appid]/users/[userid]/user_info.tsx When using href={"user_info"} with the built-in Next.js component on a user page, I expect the URL to dynamic ...