html - Angular CLI 组件和指令 CSS/SASS 属性和变量

标签 html css angular sass angular-cli

我正在做一个 Angular 6 元素,遇到了一个我不确定如何解决的情况。我正在编写一系列组件和指令,并将 SCSS 用于我的样式,其中包含用于控制布局和主题的变量。

我想要完成的是我想将所有样式保留在 SCSS 文件中,但在我的一些指令中,使用装订线设置而不是填充/边距更有意义,所以我试图构建我的组件来计算自己的边距和填充。问题是我如何定义一个“Gutter”css 属性(可能类似于他们定义::ng-deep 的方式)或者一个 css 变量来保存值?或者另一种能够在一个文件中定义所有布局和主题变量的方法?

我想到的实现此目的的唯一方法是创建一个 .json 配置文件来保存主题和其他变量,然后将其导出/导入到 SCSS 变量文件中,然后照常使用它。然后我可以将同一个文件导入到我的 Angular 组件和指令中以使用这些变量。我正在努力避免仅使用边距并将其设置为装订线之类的事情,我希望尽可能保持整洁和可读性。

也许是这样的:

layout.json

{
   appGutter: 50px, 
   appFontSize: 1em,
   (…)
}

布局.scss

@import 'layout.json'

// convert layout.json to SCSS variables 

app-root{
   font-size: $appFontSize;
} 

layout.directive.ts

@Directive({
  selector: '[pmnAppLayout]',
})
export class PmnAppLayoutDirective implements (…) {
   @HostBinding('style.margin') margin: string;

   (…)

   private _updateLayout() {
      /* Get value from json config file */
      var number = jsonCfg.appGutter;

    this.margin = `${gutter / 2}px`;
  }
}

这是基本的想法,不仅仅是排水沟,这是我能想到的唯一简单传达我的问题和可能的解决方案的方法。这似乎分配了额外的工作,有没有更好的方法来处理这个问题?

最佳答案

看起来有一种简单的方法可以处理这个问题,如果在 body 标记中声明了一个 CSS 变量,您可以使用 getComputedStyle 在 Angular 中检索该变量值。这样您就不必创建任何 .json 配置文件。您需要做的就是在 map 中定义您的变量,这样它们就可以作为 CSS 变量导出到正文(或其他标签)中,然后在 Angular 中读取它们。下面是如何完成此操作的示例。

_变量.scss

/*** Export SCSS variables to CSS ***/
@mixin PmnExportVariables($map, $prefix: null) {
  $mapPrefix: "--#{$prefix}";

  @if ($prefix){
    $mapPrefix: "#{$mapPrefix}-";
  }

  body {
    @each $name, $value in $map {
      #{$mapPrefix}#{$name}: $value;
    }
  }
}

$pmnLayout: ( 
   appGutter: 50px, 
   appFontSize: 1em,
);

@include PmnExportVariables($pmnLayout);

// To use the variable there are two options map-get and var()
app-root{
   font-size: map-get($pmnLayout, '--appFontSize');
   // font-size: var(--appFontSize);
}

layout.directive.ts

@Directive({
  selector: '[pmnAppLayout]',
})
export class PmnAppLayoutDirective implements (…) {
   @HostBinding('style.margin') margin: string;

   (…)

   private _updateLayout() {
      // Get values from the body and convert to style
      let bodyStyles = window.getComputedStyle(document.body);

      /* Get the value*/
      var tVal = bodyStyles.getPropertyValue("--appGutter");

      this.margin = `${tVal / 2}px`;
  }
}

关于html - Angular CLI 组件和指令 CSS/SASS 属性和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907585/

相关文章:

html - 如何使用 Bootstrap 5 让 Div 部分 float 到另一个 Div 的底部(或中心)

javascript - Angular-gettext 不会更新代码中生成的字符串

jquery - 关闭其内容上的滑动到顶部 Accordion

html - 响应式设计 div 不随屏幕宽度扩展

javascript - 如何访问Angular 2中VideoJs函数中的成员变量和方法?

jquery - 我的 jQuery 动画中的 div 元素 'jumps'

javascript - 根据选中的复选框获取 <td> 的值

css - 自定义复选框在 Windows 上的 Chrome 中不起作用

javascript - Angular CLI "ng e2e": missing localStorage in protractor tests with ts-node

Angular2 变化检测问题。如果类字段没有更改,但输入字段值不同,则输入字段不会更新