Back

Technologies:

javascriptjavascript
csscss
avatar
Tolerim
2 hours ago

How do I apply styling to the dropdown options within an Angular Material menu?

As an Angular developer, I'm facing issues while implementing a dropdown menu using Angular Material (MatMenuModule and MatButtonModule). The HTML code that I'm using for the menu is as follows:

<p>
        Display the daily data for a different year:
        <button mat-button class="selectYearButton" [matMenuTriggerFor]="menu">Select year</button>
        <mat-menu #menu="matMenu">
            <button mat-menu-item class="yearOptionButton" *ngFor="let year of years" (click)="updateDailyChart(year)">{{year}}</button>
        </mat-menu>
</p>

The CSS style I applied to ".selectYearButton" and ".yearOptionButton" is not working as expected except for the "font-style" property. The menu is looking too bulky compared to the rest of the text, and the font isn't matching either. Here's a screenshot of the issue: https://ibb.co/TrqqSz4 I've tried searching for a solution online, but the documentation for Angular Material is limited, and most of the solutions I found in forums didn't solve my problem. Can someone please assist me with this issue?
Answers(1)
avatar
Tolerim
2 hours ago
Verified Answer
It seems that the issue with the styles not working on your dropdown menu buttons is related to the View Encapsulation. Since you have set ViewEncapsulation.None, your styles defined in the component's CSS file may collide with global styles, and that could be overriding your custom styles. To fix this issue, instead of using ViewEncapsulation.None, you can try using ViewEncapsulation.Emulated or ViewEncapsulation.ShadowDom. These options will enable Angular to encapsulate the component's styles and avoid global style conflicts. Regarding the font family not matching, you can try explicitly setting the font family for the buttons. For example, you can add the following CSS rules to your .selectYearButton and .yearOptionButton classes:
font-family: 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
Make sure to remove the !important declaration from the .yearOptionButton class so that it takes the font family defined in the parent class. Here's the updated CSS:
.selectYearButton {
    background-color: gainsboro;
    border-style: solid;
    border-width: 1px;
    height: 30px;
    letter-spacing: .05rem;
    font-weight: 400;
    font-family: 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

.yearOptionButton {
    height: 10px;
    font-style: italic;
    font-family: 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
I hope this helps! Let me know if you have any other questions.
;