Access scoped Material theme in custom component

34 views Asked by At

In Material, you can define scoped themes to style just a portion of your app:

// config.scss
$my-special-theme: mat.define-light-theme(/*omitted*/));
.my-scope {
  @include mat.button-color($my-special-theme);
}
<!-- container.component.html -->
<section class="my-scope">
  <button mat-button color="primary">Foo</button>
  <app-bar></app-bar>
</section>

That button will be styled using the primary color from the special (scoped) theme.

What I'd like to know is: how can I use the same mechanism for my custom components? What I currently have is:

// bar.component.scss
@use 'sass:map';
@use '@angular/material' as mat;
@use 'config' as config;

$color-config: mat.get-color-config(config.$my-special-theme);
$primary: map.get($color-config, 'primary');

:host {
  background-color: mat.get-color-from-palette($primary, 100);
}

But that means I need to specify the theme twice to use it:

  1. In bar.component.scss with mat.get-color-config(config.$my-special-theme) (explicitly styles my custom component)
  2. In container.component.html with class="my-scope" (implicitly styles nested Material components)

How can I get my custom components to use the scoped styles, like Material? I think I'd rather not have to define a mixin to be included globally in config.scss, because currently my components define their styles in their own .scss files — but I'm open to suggestion.

Initial research direction: I'm trying to find a way to get the current (scoped) theme in the custom component rather than hard-coding it:

$color-config: mat.get-color-config(???);

But I suspect that isn't going to be possible.

0

There are 0 answers