Simon
Simon

Reputation: 1869

Angular Material: How do I apply custom themed typography to a CSS class outside of the theme file?

I have a custom theme file which I import into my main style file. Elsewhere in my app I have encapsulated component scss. Inside those scss files I am doing something like:

.heading-thing { @include mat-typography-level-to-styles($config, subheading-2); }

The problem here, is $config is defined in my theme file and I don't know how to access it. What I really want is a mixin that does something like

.heading-thing { @include mat-typography-apply-theme-style(subheading-2); }

Is the correct way of doing this to use @extend .mat-subheading-2;? Or is there a better way with a mixin?

Upvotes: 1

Views: 1403

Answers (1)

G. Tranter
G. Tranter

Reputation: 17918

There's an easy way to get the config that is a cheat, and there's a 'correct' way.

The easy way is to simply create it:

@import '~@angular/material/theming';
$config: mat-typography-config();

That's described here. If you've customized the typography, this won't work. But you could create your own function to return your custom config.

The 'correct' way is to implement typography customization the same way that you implement theming customization. Create a mixin that applies the typography styling, and include that mixin in a theming file for your component. Something like:

src/app/components/my-component/_my-component-theme.scss

@mixin my-component-typography($config) {

  .heading-thing {
    @include mat-typography-level-to-styles($config, subheading-2);
  }
}

This would need to be called from your global sass, where the typography config is passed in to the mixin:

@import '~@angular/material/theming';

/* gui theming and typography mixins and globals */
@import 'src/app/components/my-component/my-component-theme';

$config: mat-typography-config(); // or customize
@include angular-material-typography($config);

/* customize components */
@include my-component-typography($config);

You'll have to change whatever you need to customize your typography.

This is what Angular Material does, and as you probably see it mirrors how theming is customized. See their code here.

As for 'bloat', remember that SASS is compiled down to CSS, and the compiler should discard anything unused.

Upvotes: 2

Related Questions