Home > OS >  How to disable options of two mat-select based on selection of one option from one mat-select?
How to disable options of two mat-select based on selection of one option from one mat-select?

Time:01-05

I was working on a project with two dropdowns.

There I was able to dynamically disable/enable options of one dropdown, based on the option selected in another dropdown:

The ts code:

disable(obj) {
    let index = this.select2.indexOf(obj);
    if (index === -1) {
      return false;
    } else {
      return true;
    }
  }

  disable1(obj) {
    let index = this.select1.indexOf(obj);
    if (index === -1) {
      return false;
    } else {
      return true;
    }
  }

The HTML code:

<h1>Select-1</h1>
<mat-form-field appearance="outline">
  <mat-select [(value)]="select1" multiple>
    <mat-optgroup *ngFor="let item of arr1" [label]="item.type">
      <mat-option
        *ngFor="let data of item.name"
        [value]="data"
        [disabled]="disable(data)"
      >
        {{ data }}
      </mat-option>
    </mat-optgroup>
  </mat-select>
</mat-form-field>
<h1>Select-2</h1>
<mat-form-field appearance="outline">
  <mat-select [(value)]="select2" multiple>
    <mat-optgroup *ngFor="let item of arr2" [label]="item.type">
      <mat-option
        *ngFor="let data of item.name"
        [value]="data"
        [disabled]="disable1(data)"
      >
        {{ data }}
      </mat-option>
    </mat-optgroup>
  </mat-select>
</mat-form-field>

But I also want to disable/enable all the other options of two dropdown when 'All Pokemon' is selected. Like, if 'All Pokemon' is selected in the 1st dropdown then all the other options and the options of the 2nd dropdown also gets disabled. Similarly, if I unselect 'All Pokemon' the options will get enabled.

How do I proceed?

Thanks for the help, in advance.

Stackblitz demo

CodePudding user response:

Try this for your disable function:

disable(obj) {
    if(this.select1.find(x => x === 'All Pokemon')){
      if(obj !== 'All Pokemon'){
        return true;
      }
    }
    let index = this.select2.indexOf(obj);
    if (index === -1) {
      return false;
    } else {
      return true;
    }
  }

If you want it to work bidirectionally then try:

disable(obj) {
    if(this.select1.find(x => x === 'All Pokemon') || this.select2.find(x => x === 'All Pokemon')){
      if(obj !== 'All Pokemon'){
        return true;
      }
    }
    let index = this.select2.indexOf(obj);
    if (index === -1) {
      return false;
    } else {
      return true;
    }
  }

  disable1(obj) {
    if(this.select1.find(x => x === 'All Pokemon') || this.select2.find(x => x === 'All Pokemon')){
      if(obj !== 'All Pokemon'){
        return true;
      }
    }
    let index = this.select1.indexOf(obj);
    if (index === -1) {
      return false;
    } else {
      return true;
    }
  }
  • Related