我使用您的解决方案作为基础,因为我有多个图表和组件需要在 js 中设置颜色。希望在使用多个图表或使用颜色的第三方 js 组件时,这更可重用和可扩展,并且您希望这些颜色来自 Material 主题或调色板。
@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;
}
}
创建了一个_theme mixin,并在scss中传入了material theme。
@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);
}
}
}
在你的 main.scss 中
...
$theme: mat-light-theme($primary-palette, $accent-palette, $warn-palette);
@include theme-emitter($theme);
然后在你想要使用这些颜色的组件内部:
<app-theme-emitter></app-theme-emitter>
@ViewChild(ThemeEmitterComponent) theme: ThemeEmitterComponent;
这对我来说似乎工作得很好,你觉得呢?
I submitted this as a feature request for Material2.