Angular Material Select : Custom Style

By Arvind Rai, May 15, 2024
To customize panel style of Angular Material select, we need to use panelClass and panelWidth properties of <mat-select> directive.

panelClass

panelClass accepts classes that is used by select panel. It uses same syntax as ngClass.
Find the panelClass property of <mat-select>.
@Input()
panelClass: string | string[] | Set<string> | { [key: string]: any; } 
To customize the panel style of select, use its .mat-mdc-select-panel class.
.city-select.mat-mdc-select-panel {
  background-color: antiquewhite;
} 
Use panelClass as below.
<mat-select [formControl]="city" panelClass="city-select">
    ------
</mat-select> 

panelWidth

The panelWidth is a property of <mat-select> to configure panel width.
@Input()
panelWidth: string | number | null 
It accepts following values.
1. Any numeric value : Panel size will be as specified value.
TS
cityPanelWidth = "200px"; 
HTML
<mat-select [formControl]="city" [panelWidth]="cityPanelWidth">
 ------
</mat-select> 
2. auto : Panel will match the trigger width. It is default value.
<mat-select [formControl]="user" panelWidth="auto">
 ------
</mat-select> 
3. null or empty string : Panel will grow its width to match longest text.
<mat-select [formControl]="city" panelWidth="">
 ------
</mat-select> 

Example

item.component.ts
<h3>With panelClass</h3>
<mat-form-field>
  <mat-label>Select City</mat-label>
  <mat-select [formControl]="city" panelClass="city-select">
    @for (city of allCities; track city) {
    <mat-option [value]="city">{{city}}</mat-option>
    }
  </mat-select>
</mat-form-field>

<h3>With panelWidth</h3>
<mat-form-field>
  <mat-label>Select User</mat-label>
  <mat-select [formControl]="user" [panelWidth]="cityPanelWidth">
    @for (user of allUsers; track user) {
    <mat-option [value]="user">{{user}}</mat-option>
    }
  </mat-select>
</mat-form-field> 
item.component.ts
import { Component } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatSelectModule } from '@angular/material/select';

@Component({
  selector: 'app-item',
  standalone: true,
  imports: [MatFormFieldModule, MatSelectModule, ReactiveFormsModule],
  templateUrl: 'item.component.html'
})
export class ItemComponent {
  city = new FormControl('');
  user = new FormControl('');
  cityPanelWidth = "300px";
  allCities = [
    'Seattle',
    'Portland',
    'Los Angeles'
  ];
  allUsers = [
    'Joseph',
    'Charles',
    'Daniel',
    'Matthew'
  ];
} 
styles.css
.city-select.mat-mdc-select-panel {
  background-color: antiquewhite;
  height: 300px;
  width: 200px;
  margin: 10px;
} 
Find the print-screen of the output.
Angular Material Select : Custom Style

Reference

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE












©2024 concretepage.com | Privacy Policy | Contact Us