AngularでのCSSクラス一括バインディング

ディレクティブ ngClass を使用すると、 タグ内のCSSクラスのセットを一度に有効または 無効にすることができます。このディレクティブは、 キーをクラス名、値をブール値とするオブジェクトを 値として受け取ります。クラスは、その値が true に設定されている場合は有効になり、 false の場合は無効になります。

実際に見てみましょう。以下のクラスがあるとします:

app/app.component.css.blue {
  color: blue;
}

.bold {
  font-weight: bold;
}

例を通して、これらのクラスをブロックに対して 有効または無効にする方法を見てみましょう。

例

1つのクラスを有効にし、もう1つを無効にします:

app/app.component.html<div [ngClass]="{blue: true, bold: false}">
  text
</div>

例

クラスの状態がクラスのプロパティに 格納されているとします:

app/app.component.tsexport class AppComponent {
  public isBlue: boolean = true;
  public isBold: boolean = false;
}

クラスの可視性を、私たちのプロパティの値に 応じてバインドしましょう:

app/app.component.html<div [ngClass]="{blue: isBlue, bold: isBold}">
  text
</div>

例

プロパティには、クラスとその状態を持つ オブジェクト全体を格納することができます:

app/app.component.tsexport class AppComponent {
  public styles = {
    blue: false,
    bold: true,
  }
}

このオブジェクトをブロックにバインドしましょう:

app/app.component.html<div [ngClass]="styles">
  text
</div>

例

オブジェクトの値をクラスの他のプロパティから 取得することもできます:

app/app.component.tsexport class AppComponent {
  public isBlue: boolean = false;
  public isBold: boolean = true;

  public styles = {
    blue: this.isBlue,
    bold: this.isBold,
  }
}

このオブジェクトをブロックにバインドしましょう:

app/app.component.html<div [ngClass]="styles">
  text
</div>

実践タスク

Задание 1

2つのCSSクラスを作成してください。 1つはブロックの背景を定義し、もう1つは フォントサイズを定義するようにします。

Задание 2

2つのボタンを作成してください。 最初のボタンをクリックすると最初のクラスが トグル(切り替わり)、2番目のボタンをクリックすると 2番目のクラスがトグルするようにします。