フロントエンドエンジニア芸人もりたけんじのAngular2とTypeScriptのお勉強

Angular2 for TypeScriptのお勉強-sample(12)【ngStyleとstyle属性にbindingの違い】

Angular2 for TypeScriptのお勉強-sample(12)【ngStyleとstyle属性にbindingの違い】

フロントエンドエンジニア芸人もりたけんじのAngular2とTypeScriptのお勉強
フロントエンドエンジニア芸人もりたけんじのAngular2とTypeScriptのお勉強

チュートリアルでいうここここ読んでいます。

style属性をbindingする方法とngStyleとの違いは何なのか。

これは前回のclass属性をbindingするのとビルドインdirectiveのngClassとの違いと似ていますね。

今回のコード

のhtmlとtsファイルに書き起こしました。

Style属性をbinding

<div [style.font-size]="isSpecial ? 'x-large' : 'smaller'">This div is x-large.</div>

「""」のテンプレートステートの中で値をセットしています。

この方法だと2、3つとなった場合htmlを汚してしまいます(class使えよなのですが、、)
ビルドインdirectiveのngStyle

こちらのbild-in-directiveの方ngStyleは同時に多くのinline-styleを定義したい場合有効なのですね。

下の様に関数で呼び出して返り値でtrueなstyleを有効にしている。

htmlはこうで、
<div [ngStyle]="setStyle()"> This div is italic, normal weight, and extra large (24px)</div>

componentの方は(インデント整ってなくてごめんなさい。なんかできない)

export class ChildComponent {
canSave:boolean = true;
isUnchanged: boolean = false;
isSpecial: boolean = true;
setStyle(){
let styles = {
'font-style': this.canSave ? 'italic' : 'normal' ,
'font-weight': this.isUnchanged ? 'bold' : 'normal',
'font-size' : this.isSpecial ? '24px' : '8px',
};
return styles;
}
}

のようにして、

三項演算子で値をsetしていますね。

ngClassの回と同じですね。

でわまた〜〜

他のAngular2記事

他のjavascript記事