Search code examples
angularwidth

Angular change mat-select width dynamically based on length of selected element


I am atempting to solve this problem to set the width of the dropdown dynamically when a long string is selected. Tried to set width:"auto" or fit-content but seem not to work.

Hoping somebody can help me out here. Stackblitz link is bellow:

https://stackblitz.com/edit/angular-mat-select-testing?file=src/app/app.component.html


Solution

  • Working demo in this demo StackBlitz Demo

    You need to add below css code in app.component.scss..

    ::ng-deep .auto-width {
        .mat-form-field {
           width: auto !important;
        }
        .mat-select-value {
           max-width: 100%;
           min-width: 100%;
        }
     }
    

    In order to detect and apply style to deep level component you need to add ::ng-deep before class name .auto-width. and other option is you can add .auto-width class inside style.scss file so that every component will use this global css configuration.