Chris B
Chris B

Reputation: 31

Angular Material Component not inheriting class

I'm using angular material themes with a default light theme applied and then a dark theme applied if the class .dark-theme is on an element. I'm running into an issue though where angular material components being used don't inherit this class from parent elements.

Here's a sample component showing the issue:

<div class="dark-theme">
    <h2>Hello world</h2>
    <div class="menu-button">
        <button
            color="accent"
            mat-icon-button
            [matMenuTriggerFor]="menu"
            aria-label="Dropdown menu of available pages"
        >
            <mat-icon>menu</mat-icon>
        </button>
        <mat-menu #menu="matMenu">
            <button (click)="log('home clicked')" mat-menu-item>Home</button>
        </mat-menu>
    </div>
</div>

the component from the above code

I'm expecting the code above to give the mat-menu component the dark-theme class. If I apply the class directly <mat-menu class="dark-theme" #menu="matMenu"> it works as expected and I see the menu in a dark theme. Furthermore, I tried just giving up and doing that but dynamically assigning the class in my actual component using a BehaviorSubject and service doing [class.dark-theme]="stateService.isDarkModeEnabled()" but this still fails to apply the dark-theme class when the dark mode variable is enabled.

I don't think this is the issue, but for reference here's how my styles are defined in custom-styles.scss which is included in the angular.json.

@include mat.all-component-themes($default-theme);

:root {
    --primary-default: #{mat.get-theme-color($default-theme, primary, default)};
}

.dark-theme {
    @include mat.all-component-themes($dark-theme);
    --primary-default: #{mat.get-theme-color($dark-theme, primary, default)};
}

Upvotes: 0

Views: 74

Answers (1)

Chris B
Chris B

Reputation: 31

I think I've got this figured out finally, this post was helpful: How to add a class to dynamically rendered angular material components

I didn't realize that the cdk overlay container is not a part of the main app component itself. Also I don't understand why [ngClass] didn't work and also [class.dark-theme] didn't work yet doing [class] did work.

Upvotes: 0

Related Questions