Search code examples
typescriptangular7

Disable selected option of one dropdown for all other dropdown


I have multiple dropdowns which contain the same array values, I want to disable option which is selected in one dropdown for other dropdowns so how can I achieve that?

 <div>
    <div>
      <label >Name</label>
    </div>
    <div >
      <select >
        <option value="">Select</option>
        <option *ngFor="let type of Demo">{{type}}</option>
      </select>
    </div>
  </div>

 <div>
    <div>
      <label >Number</label>
    </div>
    <div >
      <select >
        <option value="">Select</option>
        <option *ngFor="let type of Demo">{{type}}</option>
      </select>
    </div>
  </div>

.ts File
Demo = ['One', 'Two','Three']

Solution

  • Try this

    <div>
      <div>
        <label >Name</label>
      </div>
      <div >
        <select [(ngModel)]="selectedValues[0]">
          <option value="">Select</option>
          <option *ngFor="let type of Demo" [ngValue]="type" [disabled]="isDisabled(type)">{{type}}</option>
        </select>
      </div>
    </div>
    
    <div>
      <div>
        <label >Number</label>
      </div>
      <div >
        <select [(ngModel)]="selectedValues[1]">
          <option value="">Select</option>
          <option *ngFor="let type of Demo" [ngValue]="type" [disabled]="isDisabled(type)">{{type}}</option>
        </select>
      </div>
    </div>
    
    Demo = ['One', 'Two', 'Three']
      selectedValues = [];
      isDisabled(value) {
        return this.selectedValues.includes(value);
      }
    

    If you have 20 dropdown, put the html code to *ngFor and bind the label, value to its.