Home > Net >  How to disable options from mat-select based on option selected?
How to disable options from mat-select based on option selected?

Time:10-07

I was working on a project involving mat-select. I have two mat-selects,there I want to do two things:

  1. When I select 'all' option in either of the mat-selects all the other options should get disabled.
  2. When I select an option in one mat-select,that option needs to get disabled in the other mat-select This is the stackblitz link of the project

Thanks in advance, for the help

CodePudding user response:

Use this in you second optiongroup

<mat-optgroup *ngFor="let group of testList" [label]="group.displayName">
  <mat-option *ngFor="let num of group.pokemon; let i = index"
  [value]="num"
  disabled="{{ include.includes(num) || include.includes('all') }}"
  >
    {{ num }}
  </mat-option>
</mat-optgroup>

CodePudding user response:

Problem with above solution is if somebody select all all other option including both "all' option will be disabled.You can also change your data something like this to achive your second requirement.

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

and in html

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

and now we can write our logic here

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

  }

i have edited your stackblitz. please upvote/select if helps.

  • Related