Ionic 2)で、ファイル「[my project]\src\theme\variables.scss」から$colors
変数にアクセスしたいと思います。
このファイルには以下が含まれます。
$colors: (
primary: #387ef5,
secondary: #32db64,
danger: #f53d3d,
light: #f4f4f4,
dark: #222,
favorite: #69BB7B
);
コンポーネントでは、キャンバスを描画します。次のようになります。
import {Component, Input, ViewChild, ElementRef} from '@angular/core';
@Component({
selector: 'my-graph',
})
@View({
template: `<canvas #myGraph class='myGraph'
[attr.width]='_size'
[attr.height]='_size'></canvas>`,
})
export class MyGraphDiagram {
private _size: number;
// get the element with the #myGraph on it
@ViewChild("myGraph") myGraph: ElementRef;
constructor(){
this._size = 150;
}
ngAfterViewInit() { // wait for the view to init before using the element
let context: CanvasRenderingContext2D = this.myGraph.nativeElement.getContext("2d");
// HERE THE COLOR IS DEFINED AND I D LIKE TO ACCESS variable.scss TO DO THAT
context.fillStyle = 'blue';
context.fillRect(10, 10, 150, 150);
}
}
ご覧のとおり、このコードのある時点で形状の色が定義されています:context.fillStyle = 'blue'
、代わりにcontext.fillStyle = '[variables.scss OBJECT].$colors.primary '
のようなものを使用したいと思います。
誰もがアイデアを持っていますか?
残念ながら、TypeScript/javascriptコードからSASS変数に直接アクセスする方法はありません。ただし、これらの変数にアクセスするための回避策を講じることができます。
TypeScriptソースコード内からSASS変数にアクセスする手順を簡単に説明しましょう。
作成../providers/sass-helper/sass-helper.component.scss:
$prefix: "--"; //Prefix string for custom CSS properties
//Merges a variable name with $prefix
@function custom-property-name($name) {
@return $prefix + $name;
}
// Defines a custom property
@mixin define-custom-property($name, $value) {
#{custom-property-name($name)}: $value;
}
body {
// Append pre-defined colors in $colors:
@each $name, $value in $colors {
@include define-custom-property($name, $value);
}
// Append SASS variables which are desired to be accesible:
@include define-custom-property('background-color', $background-color);
}
このSCSSファイルでは、DOMのbodyセクション内にカスタムプロパティを作成するだけです。 mixinと呼ばれるdefine-custom-property
を使用して、このSCSSファイルにアクセスできるようにする各SASS変数を追加する必要があります。
例として、$colors
で定義されているすべての色のエントリと、theme/variablesで定義されているSASS変数$background-color
のエントリを追加しました。 scssファイル。必要な数の変数を追加できます。
作成../providers/sass-helper/sass-helper.component.ts:
import { Component } from '@angular/core';
export const PREFIX = '--';
@Component({
selector: 'sass-helper',
template: '<div></div>'
})
export class SassHelperComponent {
constructor() {
}
// Read the custom property of body section with given name:
readProperty(name: string): string {
let bodyStyles = window.getComputedStyle(document.body);
return bodyStyles.getPropertyValue(PREFIX + name);
}
}
これからは、標準のIonic2コンポーネントの統合と使用のためのフレームワークの原則に従うことができます。
これらのマジック変数にアクセスするページのHTMLテンプレートに次のHTMLコードを挿入します。
<sass-helper></sass-helper>
ページのTSファイルで、次の行をページクラスに挿入する必要があります。
@ViewChild(SassHelperComponent)
private sassHelper: SassHelperComponent;
最後に、次のように子クラスメソッドを呼び出すだけで、SASS変数の値を読み取ることができます。
// Read $background-color:
this.sassHelper.readProperty('background-color');
// Read primary:
this.sassHelper.readProperty('primary');
1つの可能性は、生成.ts
ファイルから.scss
ファイルにすることです。このプロセスの簡単な例:
1)npm i --save-dev scss-to-json
をインストールします。
2)package.json
にこれを入れてください:
"scripts": {
...
"scss2json": "echo \"export const SCSS_VARS = \" > src/app/scss-variables.generated.ts && scss-to-json src/variables.scss >> src/app/scss-variables.generated.ts"
},
npm run scss2json
で実行します。 Windowsユーザーは例を調整する必要があります。
3)変数にアクセスします。
import {SCSS_VARS} from './scss-variables.generated';
...
console.log(SCSS_VARS['$color-primary-1']);
この利点の1つは、IDEからタイプ補完を取得できることです。これは、一般的に目標を達成するための非常に簡単な手段です。
もちろん、例えば、生成されたファイルを読み取り専用にし、スクリプトをそれ自身の.js
ファイルに入れて、すべてのOSで動作させることにより、これをより高度にすることができます。
@ mete-cantimurの回答に何か付け加えたいと思います。
import {Component, OnInit, ViewEncapsulation} from '@angular/core';
const PREFIX = '--';
@Component({
selector: 'app-styles-helper',
templateUrl: './styles-helper.component.html',
styleUrls: ['./styles-helper.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class StylesHelperComponent implements OnInit {
ngOnInit(): void {
}
readProperty(name: string): string {
const bodyStyles = window.getComputedStyle(document.body);
return bodyStyles.getPropertyValue(PREFIX + name);
}
}
ヘルパーコンポーネントは、ボディスタイルを変更できませんでした。すべてを正しく設定しても、カスタムプロパティは保存されませんでした。
ボディスタイルを変更できるようにするために、encapsulation: ViewEncapsulation.None
をコンポーネントに追加する必要がありました。
お役に立てれば。