How can you block a specific drop-down choice in Angular 2?

TS FILE

import { Component, ViewChild } from '@angular/core';


/**
 * @title Basic select
 */
@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})


export class SelectOverviewExample {
  resData = {
    "data": ["Pune", "Mumbai", "Pimpari", "Nagpur", "Hydrabad", "Assam", "Karnataka", "Bihar", "Maharashtra", "Delhi", "Srinagar", "Shimla", "Goa",  "Rajasthan", "MP", "Aandhra-Pradesh"]
  }
  selectOne : string ='';
  selectTwo='';
  selectThree='';
  selectFour='';
  one='';

   @ViewChild('select2') _select2: any
   firstSelections: string = '';

//    setFirstValues(form) {
//      this.firstSelections = form.value.select1
//      if (this._select2.value) {
//        const secondSelectionsValues = this._select2.value.slice();
//        for (var i = secondSelectionsValues.length - 1; i >= 0; i--) {
//          if (this.firstSelections.includes(secondSelectionsValues[i])) {
//              secondSelectionsValues.splice(i, 1)
//            this._select2.writeValue(secondSelectionsValues);
//          }
//        }
// }
// }


onChanged(){
  this.resData.data.forEach(ele =>{
if(ele == this.selectOne)
this.selectTwo !== this.selectOne;
  })
  }
}

HTML

<form #myForm="ngForm">


  <div class="col-md-4">
<mat-form-field >
    <mat-select [(ngModel)]="selectOne" name="selectOne" (selectionChange)="onChanged()">
        <mat-option *ngFor="let time1 of resData.data" value="time1" >{{time1}}</mat-option>
    </mat-select>
</mat-form-field>
  </div>

<div class="col-md-4">
    <mat-form-field >
        <mat-select [(ngModel)]="selectTwo"  name="selectTwo"  (selectionChange)="onChanged()">
            <mat-option *ngFor="let time2 of resData.data" value="time2"  >{{time2}}</mat-option>
        </mat-select>
    </mat-form-field>
</div>
<div class="col-md-4">
    <mat-form-field>
        <mat-select  [(ngModel)]="selectThree" name="selectThree">
            <mat-option *ngFor="let time3 of resData.data" value="time3" >{{time3}}</mat-option>
        </mat-select>
    </mat-form-field>
</div>
<div class="col-md-4">
    <mat-form-field>
        <mat-select [(ngModel)]="selectFour" name="selectFour">
            <mat-option *ngFor="let time4 of resData.data" value="time4" >{{time4}}</mat-option>
        </mat-select>
    </mat-form-field>
</div>
<form>

Explanation: when I select a value in the first dropdown, that value is disabled in dropdowns two, three, and four. Each dropdown must have a unique value, ensuring no duplicate values. Should I use the (selectionchange) or (ngModelChange) events for this functionality? Thank you in advance.

Check out my stackblitz example here - https://stackblitz.com/edit/on-change-selection?file=app%2Fselect-overview-example.html

Answer №1

When creating a form in HTML ::

<form #myForm="ngForm">


  <div class="col-md-4">
<mat-form-field >
    <mat-select [(ngModel)]="selectOne" name="selectOne" (selectionChange)="onChanged(selectOne)">
        <mat-option *ngFor="let time1 of resData.data" [value]="time1" >{{time1}}</mat-option>
    </mat-select>
</mat-form-field>
  </div>

<div class="col-md-4">
    <mat-form-field >
        <mat-select [(ngModel)]="selectTwo"  name="selectTwo"  (selectionChange)="onChanged(selectTwo)">
            <mat-option *ngFor="let time2 of resData.data" [value]="time2"  >{{time2}}</mat-option>
        </mat-select>
    </mat-form-field>
</div>
<div class="col-md-4">
    <mat-form-field>
        <mat-select  [(ngModel)]="selectThree" name="selectThree">
            <mat-option *ngFor="let time3 of resData.data" [value]="time3" >{{time3}}</mat-option>
        </mat-select>
    </mat-form-field>
</div>
<div class="col-md-4">
    <mat-form-field>
        <mat-select [(ngModel)]="selectFour" name="selectFour">
            <mat-option *ngFor="let time4 of resData.data" [value]="time4" >{{time4}}</mat-option>
        </mat-select>
    </mat-form-field>
</div>
<form>

For the TypeScript on change event ::

onChanged(event){
  console.log(this.resData.data[0]);
this.resData.data = this.resData.data.filter(ele => ele !== event);
console.log(this.resData);
}

Fingers crossed that this solution works for you!

Answer №2

If you want to filter already selected data, you can create a custom pipe for that purpose.

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({
  name: 'cityFilter',
  pure: false
})
export class CityFilterPipe implements PipeTransform {
  transform(items: any[], selectedItems: any[]): any {
    return items.filter(item => selectedItems.indexOf(item) < 0);
  }
}

After creating the pipe, you can use it in conjunction with *ngFor as shown below:

<form #myForm="ngForm">
    <div class="col-md-4">
        <mat-form-field>
            <mat-select [(ngModel)]="selectOne" name="selectOne">
                <mat-option *ngFor="let time1 of resData.data" [value]="time1">{{time1}}</mat-option>
            </mat-select>
        </mat-form-field>
    </div>

    <div class="col-md-4">
        <mat-form-field>
            <mat-select [(ngModel)]="selectTwo" name="selectTwo">
                <mat-option *ngFor="let time2 of resData.data | cityFilter:[selectOne]" [value]="time2">{{time2}}         </mat-option>
            </mat-select>
        </mat-form-field>
    </div>
    <div class="col-md-4">
        <mat-form-field>
            <mat-select [(ngModel)]="selectThree" name="selectThree">
                <mat-option *ngFor="let time3 of resData.data | cityFilter:[selectOne,selectTwo]" [value]="time3">{{time3}}</mat-option>
            </mat-select>
        </mat-form-field>
    </div>
    <div class="col-md-4">
        <mat-form-field>
            <mat-select [(ngModel)]="selectFour" name="selectFour">
                <mat-option *ngFor="let time4 of resData.data| cityFilter:[selectOne,selectTwo, selectThree]" [value]="time4">{{time4}}</mat-option>
            </mat-select>
        </mat-form-field>
    </div>
<form>

Check out the demo here.

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

Ensure all promises are resolved inside of for loops before moving on to the next

Within my angular 11 component, I have a process that iterates through elements on a page and converts them from HTML to canvas to images, which are then appended to a form. The problem I am encountering is that the promise always resolves after the ' ...

Revise regular expression for verifying addresses

In my angular app, I have created a regular expression for validating postal addresses. const regx = '\\b([p]*(ost)*\\.*\\s*[o|0]*(ffice)*\\.*\\s*b[o|0]x)\\b' I specifically want this ...

Show the chosen choice in a select dropdown with custom text using Angular

I successfully implemented this code snippet to display a dropdown list of countries and their phone codes. However, I encountered an issue where I need to only show the selected option's code without the country name. The first screenshot shows how i ...

Advantages of creating model classes in Angular 2 and above

When developing a service for my domain, I discovered that I could easily implement the service using any type like this: list(): Observable<any> { const url = this.appUrlApi + this.serviceUrlApi; return this.http.get(url, { headers: this.he ...

Creating an interactive webpage with Javascript and HTML

I'm facing a challenge with my component setup, which is structured as follows: import { Component, VERSION } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ ...

Updating the state of the Store using NGRX

As I work on writing unit tests to evaluate the functionality of my NGRX store in Angular 10 with NGRX 10, I have been setting actions to manipulate the state as needed. Then, I run the test for the action and verify that it changes the state accordingly. ...

Ways to transfer selected options from a dropdown menu to a higher-level component

I am currently in the process of configuring a modal component that showcases various data from a specific record to the user. The user is provided with a Bulma dropdown component for each field, enabling them to make changes as needed. To streamline the c ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...

Encountering an issue connecting to the backend server for the

I am attempting to make a POST request from my Angular 2 frontend to my Spring backend, but I am encountering an error. The error message: GET http://localhost:8080/loginPost 405 () Failed to load http://localhost:8080/loginPost: No 'Access-Control ...

Can we resolve the warnings arising from third party dependencies in a React application?

After running the pnpm install command to set up dependencies for a react app today, I encountered the following warning messages: > pnpm install  WARN  deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f18287969 ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

Exploring the process of retrieving token expiration in TypeScript using the 'jsonwebtoken' library

Currently utilizing jsonwebtoken for token decoding purposes and attempting to retrieve the expiration date. Encountering TypeScript errors related to the exp property, unsure of the solution: import jwt from 'jsonwebtoken' const tokenBase64 = ...

Leveraging foreign key attributes within Angular templates

My technology stack includes Django for the backend with Django Rest Framework and Angular for the frontend. Within the backend, I have defined 2 models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null= ...

Leveraging the Angular (2) routerLinkActive directive to handle dynamic routes

Although my current approach works, I believe there may be a more efficient way to implement this in Angular. The situation is as follows: Imagine nested, inflected paths like /logos and /logo/:id The markup below functions as intended: <li class ...

What causes the appearance of the "?" symbol at the beginning of the URL and triggers a reboot of the app when moving through the absolute path?

I am facing an issue. In my multi-module application with lazy loading, I encountered a strange behavior when trying to navigate between child lazy modules. Transition from top module to bottom child module works fine, but routing from one bottom child la ...

I encountered difficulties accessing the native Camera API when working with the most recent version of Ionic

Every time I try to run $ ionic cordova plugin add @ionic-enterprise/camera I encounter the following error message [OK] Integration cordova added! ✔ Creating ./www directory for you - done! > cordova plugin add @ionic-enterprise/camera You have ...

A method to access a stored value in localStorage that does not involve utilizing the __zone_symbol__value property

I am encountering a problem with localStorage. After storing user information in localStorage, I am unable to retrieve it without using the __zone_symbol__value property of the parsed value. This is how I store data into locaStorage localStorage.setItem(& ...

Exploring TypeScript in the world of Shopify Command Line Interface

Exploring the process of developing a Shopify app using Typescript starting with the shopify-app-cli boilerplate, which utilizes Koa for the server and Nextjs for the frontend in React JavaScript. see https://github.com/Shopify/shopify-app-cli Encounterin ...

Nested Observables in Angular are essential for handling asynchronous

In my service, I have a function that returns an observable array of entity ids. Another function in the service takes an entity id as a parameter and returns detailed information about that entity as an observable. My goal is to retrieve all entity ids u ...

Angular array of considerable size

Dealing with a massive array of 30,000 items can be quite daunting, especially when it comes in as a stream using grpc-web. Currently, I'm fetching the data from grpc.client() and populating an array before displaying it using *ngFor. However, I' ...