How to use angular material theme color in TypeScript / JavaScript?
I used a hacky solution. It's not beautiful but working.
component.html
<div #primary class="mat-button mat-primary" style="display:none"></div>
component.ts
declare let getComputedStyle: any;
export class Component implements AfterViewInit {
@ViewChild('primary') primary: ElementRef;
ngAfterViewInit() {
const primaryColor = getComputedStyle(this.primary.nativeElement).color;
}
I used your solution as the base for this as I had multiple charts and components that needed to set colours in the js. hopefully this is more reusable and extendable when using multiple charts or third party js components that use colours and you want those colours to come from the Material theme or palettes.
@Component({
selector: 'app-theme-emitter',
template: `<div class='primary'></div>
<div class='accent'></div>
<div class='warn'></div>`,
styles: [':host { display: none; }']
})
export class ThemeEmitterComponent implements AfterViewInit {
primaryColor: string;
accentColor: string;
warnColor: string;
@ViewChild('primary') primaryElement: ElementRef;
@ViewChild('accent') accentElement: ElementRef;
@ViewChild('warn') warnElement: ElementRef;
ngAfterViewInit() {
this.primaryColor = getComputedStyle(this.primaryElement.nativeElement).color;
this.accentColor = getComputedStyle(this.accentElement.nativeElement).color;
this.warnColor = getComputedStyle(this.primaryElement.nativeElement).color;
}
}
Created a _theme mixin and passed in the material theme in the scss.
@mixin theme-emitter($theme) {
$primary: map-get($theme, primary);
$accent: map-get($theme, accent);
$warn: map-get($theme, warn);
app-theme-emitter {
.primary {
color: mat-color($primary);
}
.accent {
color: mat-color($accent);
}
.warn {
color: mat-color($warn);
}
}
}
Inside your main.scss
...
$theme: mat-light-theme($primary-palette, $accent-palette, $warn-palette);
@include theme-emitter($theme);
Then inside the component you want to consume these colours from:
<app-theme-emitter></app-theme-emitter>
@ViewChild(ThemeEmitterComponent) theme: ThemeEmitterComponent;
This is working pretty well for me it seems, what do you think?
I submitted this as a feature request for Material2.