Angular2でのstyle属性とクラス属性の指定

Angular2でのstyle属性とクラス属性の指定

Angular2かなり楽しいけど、わからないと複雑に考えがち。
今回はstyle属性とクラス名の指定方法を紹介します。

style属性の指定

<div class="box" [style.background-color]="'red'"></div>
<div class="box" [style.background-color]="isActive ? 'green' : 'grey'"></div>
<div class="box" [style.background-color]="getColor()"></div>

[style.property]の形式で指定。
テンプレートが属するコンポーネントのプロパティやメソッドの返り値をConditionsとして指定できる。
真偽値falseの場合は、除去される。

クラス属性の指定

<div [class]="box"></div>
<div [class.box]="true"></div>
<div [class.is-active]="isOpen"></div>

こちらも、テンプレートが属するコンポーネントのプロパティやメソッドの返り値をConditionsとして指定できる。
真偽値falseの場合は、除去される。

ngStyle

<div [ngStyle]="{ 'display': 'block', 'color': 'red', 'font-weight': 'bold' }"></div>

オブジェクト形式で指定。
カンマで区切れば複数指定もできる。

ngClass

<div [ngClass]="[ 'box', 'is-active' ]"></div>
<div [ngClass]="{ 'box': true, 'is-active': isActive }"></div>

配列、オブジェクト形式で指定。
配列の場合、全ての文字列がクラス名として追加される。
オブジェクトではConditionsとして指定できる。もちろん、falseの場合は除去される。

Attribute Directives

Attribute Directivesという仕組みで属性のディレクティブを作成する。
公式サイトのDocsに詳しく載っている。

この例では [styled] というディレクティブを作成する。

<div styled></div>

ElementRef というクラスを介してDOMにアクセスして、属性値を書き換える。
ElementRef.nativeElement プロパティでDOMを参照する。

import {Directive, ElementRef, Renderer} from 'angular2/core';

@Directive({
  selector: '[styled]',
})
export class StyledDirective {
  constructor(public el: ElementRef, public renderer: Renderer) {
    // el.nativeElement.style.backgroundColor = 'yellow';
    renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
  }
}
五十川 洋平(Yohei Isokawa)

五十川 洋平(Yohei Isokawa)

フロントエンドエンジニア/面白法人カヤックなどのWeb制作会社に勤務したのち、故郷の新潟に戻り独立。JSフレームワークAngularやFirebase、Google Cloud Platformを使ったWebアプリ開発が得意。 また、Udemyのプログラミング解説の講師、writer.appの自主開発や上越TechMeetupの主催などを行っています。

プロフィール

©Copyright 2022 Yohei Isokawa All Rights Reserved.