簡體   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