LoginSignup
0
0

More than 5 years have passed since last update.

Ignite UI for Angular の動的テーマ変更の方法

Posted at

2018/12/25(Tue) 時点の情報に基づいています
igniteui-angular@7.1.1

前回、Ignite UI for Angular のライト/ダークテーマの設定方法ではテーマを静的に設定する方法をご紹介しました。

今回は、動的にテーマを設定する方法のご紹介です。

Light と Dark テーマにも説明はあるのですが、ここではより具体的に、より簡潔に説明したいと思います。

テーマ切り替えの実装方法

ライトテーマ用のクラス light-theme を定義して igx-light-theme() をネストします。
ダークテーマ用のクラス dark-theme を定義してigx-dark-theme() をネストします。

styles.scss
@import "~igniteui-angular/lib/core/styles/themes/index";

@include igx-core();

body.light-theme {
    @include igx-light-theme($default-palette);
}

body.dark-theme {
    background-color: #333;
    color: #fff;

    @include igx-dark-theme($default-palette);
}

テーマ切り替え用UIの実装方法

ライトテーマ、ダークテーマを切り替えられるように、UIを用意します。使用するコンポーネントはなんでも構いません。例えばここでは select タグを使用して以下の用に実装します。

src/app.component.html
<select #select [value]="theme" (change)="themeChange(select.value)">
  <option value="light-theme">light</option>
  <option value="dark-theme">dark</option>
</select>

TypeScript側では、バインドする theme プロパティ、および、themeChange イベントハンドラを定義します。

src/app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  theme = 'light-theme'; // デフォルトではライトテーマ

  ngOnInit(): void {
    // AppComponent の初期化のタイミングで body タグに、テーマ用クラスを付与する
    document.body.classList.add(this.theme);
  }

  // select タグの変更に応じて body タグのテーマ用クラスを変更する
  themeChange(newTheme: string): void {
    // 現在のテーマを削除
    document.body.classList.remove(this.theme);
    // 新たに洗濯されたテーマを付与
    document.body.classList.add(newTheme);
    this.theme = newTheme;
  }

わざわざ body タグにテーマクラスを付与しているところがポイントです。@HostBinding では app-root タグよりも上位の body タグにCSSクラスを付与する方法がありません。app-root タグにテーマ用クラスを付与した場合、app-root タグで覆われていない部分は、テーマが切り替わらないので、body タグに付与することで、画面全体をテーマ切り替え対象としています。

実行結果

demo

ライトテーマ

image.png

ダークテーマ

image.png

まとめ

Ignite UI for Angular のコンポーネントは、igx-light-theme()igx-dark-theme() が用意されているおかげで、非常に簡単に、全体のテーマ切り替えを行うことができるようになっています。

カスタムパレットを用意すれば、ライト、ダークだけでなく、さまざまなテーマを用意することも可能です。

Ignite UI for Angular が気になった方はこちら

デモサイトで様々なサンプルを試すことができますので色々試してみてください!
https://jp.infragistics.com/products/ignite-ui-angular/angular/components/grid_virtualization.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0