Как получить оттенок / светлее из основной палитры

Итак, в Angular Material 2 у меня настроена тема

$store-primary: mat-palette($mat-storecast);
$store-accent:  mat-palette($mat-pink, A200, A100, A400);

// The warn palette is optional (defaults to red).
$store-warn:    mat-palette($mat-red);

// Create the theme object (a Sass map containing all of the palettes).
$store-theme: mat-light-theme($store-primary, $store-accent, $store-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($store-theme);

Чего я не могу понять из их документации, так это того, как получить разные цвета оттенка из основной палитры на кнопке панели инструментов.

<button md-mini-fab (click)="zoomIn()" color="primary">
     <md-icon>add</md-icon>
</button>

Похоже, он понимает только цвет = основной или цвет = акцент и т. Д. Как вы указываете, что я хочу использовать первичный-100 или первичный-500 и т. Д.?


person StevieB    schedule 22.02.2017    source источник


Ответы (3)


Официальный ответ - в настоящее время это невозможно. Атрибут color, доступный для большинства компонентов, принимает только тип палитры, то есть первичный, акцентный или предупреждающий.

Неофициальный ответ, если вы действительно хотите это сделать, заключается в том, что это возможно (на покомпонентной основе), если вы не возражаете против злоупотребления внутренними API. Например, чтобы получить цвет A100 на кнопке, вы можете добавить собственный миксин в свою тему.

// custom-button-theme.scss
@import '~@angular/material/core/theming/all-theme';
@import '~@angular/material/button/_button-theme';

@mixin custom-button-theme($theme) {

  .mat-raised-button.a100, .mat-fab.a100, .mat-mini-fab.a100 {
    // _mat-button-theme-color is a mixin defined in _button-theme.scss
    // which applies the given property, in this case background-color
    // for each of the palettes - i.e. primary, accent and warn.
    // The last parameter is the hue colour to apply.
    @include _mat-button-theme-color($theme, 'background-color', 'A100');
  }

}

Затем в основной файл темы вы импортируете собственный миксин.

@import 'custom-button-theme.scss';
@include custom-button-theme($store-theme);

Затем ваша кнопка может использовать цвет, добавив класс a100.

<button md-mini-fab (click)="zoomIn()" color="primary" class="a100">
  <md-icon>add</md-icon>
</button>

Однако важно отметить, что внутренние API-интерфейсы могут измениться в любое время. Этот код был протестирован с версией 2.0.0-beta.2 - нет гарантии, что он будет работать с бета-версией 3, когда она выйдет.

person ianjoneill    schedule 05.03.2017
comment
Хорошо, спасибо, Ян, я думаю, это будет добавлено в ближайшем будущем. - person StevieB; 06.03.2017

Я использую angular-material 1, я не уверен, что это то же самое, но я использую директиву: md-colors="::{background: 'themename-primary-100'}" Конечно, в themename вы указываете имя темы: P

person Luiz Rossi    schedule 22.02.2017
comment
Я пробовал, например, color = primary-100, но по какой-то причине он изменился на акцентную тему. Довольно странно - person StevieB; 22.02.2017
comment
вам нужно определить тему, в angular 1 это делается так: $mdThemingProvider.theme('themename') .primaryPalette('blue-grey') .accentPalette('lime') .warnPalette('red'); $mdThemingProvider.setDefaultTheme('themename'); затем вы используете md-colors="::{background: 'themename-primary-100'}" - person Luiz Rossi; 22.02.2017
comment
Пожалуйста, если он правильный, просто отметьте ответ правильно, что я все это редактирую в поле ответа, чтобы было удобнее для чтения. - person Luiz Rossi; 22.02.2017
comment
@LuizRossi Это неверно. Он спросил конкретно об angular2 и material2. - person Jeff Sheldon; 22.02.2017

Я исправил это, создав собственный миксин в компоненте scss. В этом миксине вы можете использовать основной цвет, вызвав метод map-get. Вам нужно включить миксин в свой styles.scss (где вы включаете angular-material-theme), чтобы эта работа работала. См. Пример ниже.

Создайте собственный миксин из ваших компонентов scss:

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

@mixin custom-component($theme) {
  $primary: map-get($theme, primary);

  mat-toolbar{
    &.p100{
      background-color: mat-color($primary, 100);
    }
  }
}

Присвойте панели инструментов в вашем шаблоне класс p100:

<mat-toolbar class="p100"></mat-toolbar>

Наконец, включите миксин в свой файл styles.scss, чтобы он был включен в вашу тему:

@import 'PATH_TO_YOUR_COMPONENT/custom-component.scss'; <--------- import the custom mixin

$store-primary: mat-palette($mat-storecast);
$store-accent:  mat-palette($mat-pink, A200, A100, A400);

// The warn palette is optional (defaults to red).
$store-warn:    mat-palette($mat-red);

// Create the theme object (a Sass map containing all of the palettes).
$store-theme: mat-light-theme($store-primary, $store-accent, $store-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include custom-component($store-theme); <--------- Include it before you include angular-material-theme
@include angular-material-theme($store-theme);
person Olafvv    schedule 11.07.2019