1

I have created an angular library and I would like to use the apps primary material color in my libraries css.

An application can define a primary color, assuming $app-primary is defined in my apps theme.scss. However my library of course does not have access to the parent applications variables. If my library is used in two different applications, one that defines pink as primary and one that provides blue as a primary, I would like the library to use it.

$app-primary: mat-palette($mat-blue, 600, 200, 800);
$app-theme: mat-light-theme($app-primary, $app-accent, $app-warn);
@include angular-material-theme($app-theme);

library scss:

.header {
  background-color: mat-color(...); // Can I get the applications primary color?
}

Can I obtain the applications primary theme inside my library? I would like the background color of one of my library components to match the applications primary color that it is contained in.

0

1 Answer 1

1

This is described in the theming docs. Your component must expose a mixin with the theme as a parameter, from which it can read the color:

@mixin color($theme) {
  .header {
    color: mat.get-theme-color($theme, primary, 500);
  }
}

If you have multiple components in your library which use the primary color, it makes sense to expose a separate mixin such as init() so it is easier for the applications which use the library:

@use "path-to-your-header-component" as header;

@mixin init($theme) {
  @include header.color($theme);
  // here you can add more mixins from other components
}

Final step: In your applications, you need to include this mixin:

@use "@angular/material" as mat;
@use "your-lib" as lib;

$app-theme: mat.light-theme($app-primary, $app-accent, $app-warn);

@include mat.core();
@include lib.init($app-theme);
Sign up to request clarification or add additional context in comments.

1 Comment

In my case the library is pulled in a bootstrapped dynamically. Unfortunately it will be a bit more complicated in my case. I will need to work through how to include the mixin from these libraries dynamically at compile time. Thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.