[css] Styling mat-select in Angular Material

How to style mat-select's panel component. From the docs I get that I need to provide panelClass so I make it like this:

<mat-form-field>
  <mat-select placeholder="Search for"
    [(ngModel)]="searchClassVal"
    panelClass="my-select-panel-class"
    (change)="onSearchClassSelect($event)">
    <mat-option *ngFor="let class of searchClasses" [value]="class.value">{{class.name}}</mat-option>
  </mat-select>
</mat-form-field>

I inspected in developer tools that this class is attached to the panel in DOM and it is attached. So I have my custom scss class attached to this element. Now when I provide css it just don't work. My scss for example looks like this:

.my-select-panel-class {
    width:20px;
    max-width:20px;
    background-color: red;
    font-size: 10px;
}

The width of the panel is always equal to the width of the select element. Sometimes In options You have too long strings and I would like to make it a little bit wider. Is there any way how to do this. My style from my component just not working even background-color is not working. Does somebody knows why this behaves so strange?

I'm using: Angular 4.4.5 @angular/material: 2.0.0-beta.12

This question is related to css angular typescript angular-material

The answer is


For Angular9+, according to this, you can use:

.mat-select-panel {
    background: red;
    ....
}

Demo


Angular Material uses mat-select-content as class name for the select list content. For its styling I would suggest four options.

1. Use ::ng-deep:

Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

CSS:

::ng-deep .mat-select-content{
    width:2000px;
    background-color: red;
    font-size: 10px;   
}

DEMO


2. Use ViewEncapsulation

... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.

None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:

Typscript:

  import {ViewEncapsulation } from '@angular/core';
  ....
  @Component({
        ....
        encapsulation: ViewEncapsulation.None
 })  

CSS

.mat-select-content{
    width:2000px;
    background-color: red;
    font-size: 10px;
}

DEMO


3. Set class style in style.css

This time you have to 'force' styles with !important too.

style.css

 .mat-select-content{
   width:2000px !important;
   background-color: red !important;
   font-size: 10px !important;
 } 

DEMO


4. Use inline style

<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>

DEMO


Put your class name on the mat-form-field element. This works for all inputs.


Working solution is by using in-build: panelClass attribute and set styles in global style.css (with !important):

https://material.angular.io/components/select/api

_x000D_
_x000D_
/* style.css */
.matRole .mat-option-text {
  height: 4em !important;
}
_x000D_
<mat-select panelClass="matRole">...
_x000D_
_x000D_
_x000D_


Questions with css tag:

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width Font Awesome 5 font-family issue Failed to load resource: the server responded with a status of 404 (Not Found) css CSS class for pointer cursor How and where to use ::ng-deep? Styling mat-select in Angular Material What is the difference between CSS and SCSS? iPhone X / 8 / 8 Plus CSS media queries Change arrow colors in Bootstraps carousel Bootstrap 4 Dropdown Menu not working? Add class to an element in Angular 4 CSS Grid Layout not working in IE11 even with prefixes Search input with an icon Bootstrap 4 Bootstrap 4 - Inline List? Centering in CSS Grid Bootstrap 4, how to make a col have a height of 100%? Equal height rows in CSS Grid Layout Bootstrap 4: Multilevel Dropdown Inside Navigation Align the form to the center in Bootstrap 4 Customize Bootstrap checkboxes How to style a clicked button in CSS How can I get the height of an element using css only display: flex not working on Internet Explorer force css grid container to fill full screen of device How does the "position: sticky;" property work? bootstrap 4 row height Prevent content from expanding grid items Bootstrap 4 File Input CSS hide scroll bar, but have element scrollable CSS grid wrapping Bootstrap 4 Change Hamburger Toggler Color How can I make Bootstrap 4 columns all the same height? How to hide collapsible Bootstrap 4 navbar on click Bootstrap 4 Center Vertical and Horizontal Alignment Cannot read property 'style' of undefined -- Uncaught Type Error How to window.scrollTo() with a smooth effect Vertical Align Center in Bootstrap 4 How to implement a Navbar Dropdown Hover in Bootstrap v4? CSS change button style after click What is correct media query for IPad Pro? How do I specify row heights in CSS Grid layout?

Questions with angular tag:

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7 How to set value to form control in Reactive Forms in Angular Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] WARNING in budgets, maximum exceeded for initial ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found How to set width of mat-table column in angular? How to reload current page? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How to convert string to boolean in typescript Angular 4 Angular: How to download a file from HttpClient? Confirm password validation in Angular 6 Angular 6: saving data to local storage How to use mouseover and mouseout in Angular 6 get current date with 'yyyy-MM-dd' format in Angular 4 Sort Array of object by object field in Angular 6 Setting values of input fields with Angular 6 Select default option value from typescript angular 6 Angular 6: How to set response type as text while making http call Set default option in mat-select How to do a timer in Angular 5 Can not find module “@angular-devkit/build-angular” Could not find module "@angular-devkit/build-angular" How to remove package using Angular CLI? How to add bootstrap in angular 6 project? Can't bind to 'dataSource' since it isn't a known property of 'table' Angular 6 Material mat-select change method removed How to set environment via `ng serve` in Angular 6 Angular 5 Button Submit On Enter Key Press ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]: Set focus on <input> element How to import a new font into a project - Angular 5 Angular - "has no exported member 'Observable'" Uncaught (in promise): Error: StaticInjectorError(AppModule)[options] Property '...' has no initializer and is not definitely assigned in the constructor Angular 5 ngHide ngShow [hidden] not working What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that? Angular - How to apply [ngStyle] conditions How to remove whitespace from a string in typescript? Angular 5 - Copy to clipboard

Questions with typescript tag:

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type? ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead What is "not assignable to parameter of type never" error in typescript? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How to convert string to boolean in typescript Angular 4 What is the Record type in typescript? Angular: How to download a file from HttpClient? Angular 6: saving data to local storage Sort Array of object by object field in Angular 6 How to use `@ts-ignore` for a block Setting values of input fields with Angular 6 Select default option value from typescript angular 6 Angular 6: How to set response type as text while making http call How to do a timer in Angular 5 Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Angular 5 Button Submit On Enter Key Press Importing json file in TypeScript Angular - "has no exported member 'Observable'" Property '...' has no initializer and is not definitely assigned in the constructor How to remove whitespace from a string in typescript? Angular 5 - Copy to clipboard Angular 5, HTML, boolean on checkbox is checked js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check document.getElementById replacement in angular4 / typescript? Exclude property from type How to iterate using ngFor loop Map containing key as string and values as map iteration Read response headers from API response - Angular 5 + TypeScript 'mat-form-field' is not a known element - Angular 5 & Material2 Angular 5 Scroll to top on every Route click Angular File Upload Property 'value' does not exist on type 'Readonly<{}>' No provider for Http StaticInjectorError How to get query parameters from URL in Angular 5? Angular Material: mat-select not selecting default Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf No provider for HttpClient I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular Add items in array angular 4 Angular 4 checkbox change value How to import JSON File into a TypeScript file? How to generate components in a specific folder with Angular CLI?

Questions with angular-material tag:

error TS1086: An accessor cannot be declared in an ambient context in Angular 9 @angular/material/index.d.ts' is not a module How to set width of mat-table column in angular? Confirm password validation in Angular 6 Set default option in mat-select Can't bind to 'dataSource' since it isn't a known property of 'table' Checkbox angular material checked by default How to set the color of an icon in Angular Material? Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) Styling mat-select in Angular Material Angular + Material - How to refresh a data source (mat-table) How to use paginator from material angular? How to import Angular Material in project? Angular 2 ngfor first, last, index loop Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents? Angular2 Material Dialog css, dialog size File Upload with Angular Material Choosing bootstrap vs material design