Search code examples
angularangular-materialmat-select

Angular Material - Hide disabled select option


I have a form in my app where I have a mat-select with a list of users. Users have permissions and in my select I want to show only those who have permission. I checked the documents for mat-select and can disable users but still shown as an option.

I tried to use [class-hidden] and try to hide it with CSS, but the space for the user is still there and that looks bad in the app. Is there a way to hide disabled users from select-option?

Here is my html code:

<div class="material-input">
  <mat-form-field class="form-group-select">
    <mat-label>User name</mat-label>
    <mat-select class="select" placholder="User names"
      formControlName="user">
      <mat-option  *ngFor="let user of users"
        [value]="user.id" [disabled]="user.permission === 'N'">
        {{user.name}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</div>

Solution

  • If you want to hide the disabled user(s) from <mat-option>, would recommend directly filter the element from users. Thus, the users array will only consist of the user with permission !== 'N' and these filtered users will only be displayed in <mat-option>.

    .component.ts

    // Filter users after getting data
    this.users = this.users.filter((user) => user.permission !== 'N');
    

    .component.html

    <mat-select class="select" placholder="User names" formControlName="user">
      <mat-option *ngFor="let user of users" [value]="user.id">
        {{ user.name }}
      </mat-option>
    </mat-select>
    

    Sample demo on StackBlitz