首页 > 解决方案 > Angular Material:如何将自定义主题排版应用于主题文件之外的 CSS 类?

问题描述

我有一个自定义主题文件,我将它导入到我的主style文件中。在我的应用程序的其他地方,我封装了组件 scss。在这些 scss 文件中,我正在做类似的事情:

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

这里的问题$config是在我的主题文件中定义的,我不知道如何访问它。我真正想要的是一个类似的mixin

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

这样做的正确方法是使用@extend .mat-subheading-2;吗?或者有没有更好的方法使用mixin?

标签: cssangularangular-material

解决方案


有一种简单的方法可以获取作弊的配置,并且有一种“正确”的方法。

简单的方法是简单地创建它:

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

这是描述here。如果您自定义了排版,这将不起作用。但是您可以创建自己的函数来返回您的自定义配置。

“正确”的方式是实现排版定制的方式与实现主题定制的方式相同。创建一个应用排版样式的 mixin,并将该 mixin 包含在组件的主题文件中。就像是:

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);
  }
}

这需要从您的全局 sass 中调用,其中排版配置被传递给 mixin:

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

/* TI 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);

/* TI GUI core style */
@include my-component-typography($ti-material-typography);

您必须更改自定义排版所需的任何内容。

这就是 Angular Material 的作用,你可能会看到它反映了主题化的定制方式。在这里查看他们的代码。

至于“膨胀”,请记住 SASS 被编译为 CSS,编译器应该丢弃任何未使用的内容。


推荐阅读