繁体   English   中英

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

[英]Angular CLI component and directive CSS/SASS properties and variables

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

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

我想到的唯一方法是创建一个.json配置文件来保存主题和其他变量,然后将其导出/导入到SCSS变量文件中,然后照常使用。 然后,我可以将该相同文件导入到Angular组件和指令中以使用变量。 我试图避开诸如仅使用页边距并将其设置为装订线的事情,我希望保持其清洁和可读性。

也许像这样:

layout.json

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

layout.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配置文件。 您需要做的就是在映射中定义变量,以便可以将它们作为CSS变量导出到主体(或其他标签)中,然后在Angular中读取它们。 这是如何完成此操作的示例。

_variables.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`;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM