6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Angular] コンポーネントのscssでアプリ全体で使う変数を使用する方法

Posted at

マテリアルデザインの余白の8pxとかを変数に定義してアプリ全体で使いたかったので方法を調べました。

方法

angular.jsonにstylePreprocessorOptionsを追加します。この設定だと src/sass 以下のscssファイルが、ディレクトリ名指定無しにインポートできるようになります。

angular.json
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.scss"
            ],
+            "stylePreprocessorOptions": {
+              "includePaths": [
+                "src/sass"
+              ]
+            },
            "scripts": []

次に変数を定義するファイルをsrc/sassに作成します。

src/sass/variables.scss
$single-space: 8px;
$double-space: 16px;

最後に利用したいコンポーネントのscssでインポートして使用します。

src/app/hoge.component.scss
@import "variables";

.form-action-container {
  margin-top: $double-space;
  margin-bottom: $double-space;
}

注意点はng serveは再起動する必要があるところ。

参考
https://stackoverflow.com/questions/50878691/how-to-import-sass-files-in-angular-6

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?