Angular2テンプレートでインラインスタイルをバインドするのは簡単です。 たとえば、単一のスタイル値をバインドする方法は次のとおりです。
<p [style.background-color]="'darkorchid'"> Quite something! </p>
単位を指定することもできます。たとえば、 em で単位を設定しますが、 px 、%、またはremも指定できます。使用済み:
<p [style.font-size.em]="'3'"> A paragraph at 3em! </p>
コンポーネントのプロパティに応じて、条件付きでスタイル値を設定する方法は次のとおりです。
<p [style.font-size.px]="isImportant ? '30' : '16'"> Some text that may be important. </p>
複数の値のNgStyle
単純なスタイルバインディングは単一の値に最適ですが、複数のスタイルを適用する場合、最も簡単な方法はNgStyleを使用することです。
<p [ngStyle]="myStyles"> You say tomato, I say tomato </p>
そして、myStylesは、次のように、キーとしてcssプロパティ名を持つオブジェクトを含むコンポーネントのプロパティになります。
myStyles = { 'background-color': 'lime', 'font-size': '20px', 'font-weight': 'bold' }
または、次のようにインラインで提供することもできます。
<p [ngStyle]="{'background-color': 'lime', 'font-size': '20px', 'font-weight': 'bold'}"> You say tomato, I say tomato </p>
または、オブジェクトをメソッドの戻り値にすることもできます。
<p [ngStyle]="setMyStyles()"> You say tomato, I say tomato </p>
関連するコンポーネントクラス内
setMyStyles() { let styles = { 'background-color': this.user.isExpired ? 'red' : 'transparent', 'font-weight': this.isImportant ? 'bold' : 'normal' }; return styles; }