2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ngx-color-pickerで設定したカラーコードを取得する方法

Last updated at Posted at 2020-04-01

Angular用のColorPickerのライブラリとして有名なものに ngx-color-picker というものがあります。
個人的に設定したカラーコードの取り出しに時間がかかったのでメモがてらここに残しておきます。
内容的には薄いので、寂しさを紛らわせるために導入の部分も日本語訳という大義名分のもと書きます。

導入までの手順

インストール

npm install ngx-color-picker --save

モジュールの読み込み

import { ColorPickerModule } from 'ngx-color-picker';
 
@NgModule({
  ...
  imports: [
    ...
    ColorPickerModule
  ]
})

HTMLに組み込む

<input [(colorPicker)]="color" [style.background]="color"/>

実際の表示はこんな感じ

スクリーンショット 2020-04-01 21.13.18.png

めっちゃ便利ですね。

実際の利用方法としてtext入力欄の色がそのまま変化するのは少し寂しいので、こんな感じにカラーパレットのように利用するんじゃないかなと思います。

qiita.gif

コードは以下のような感じです。
CSSは特に解説も無いのではしょります。

<section>
   <label>
      <input type="radio">
      <p class="color-pallet-custom"
         #ignoredInput
         [style.color]="color"
         [cpIgnoredElements]="[ignoredButton, ignoredInput]"
         [(cpToggle)]="toggle"
         [(cpPosition)]="top-right"
         [(colorPicker)]="color"></p>
   </label>
   <button #ignoredButton (click)="toggle=!toggle" class="btn-primary" type="button" ngbButtonLabel>色選択</button>
  </section>

本題

ここまで設定できて『(゚∀゚)イイ!!』 ってなってたんですけど、どうやって値取り出すんだって結構試行錯誤しました。実際はこんな感じで取り出せます。

コード

<input type="radio" [value]="this.color">

簡単ですね。
例えばreativeformを使って実装する際などはこのような形で値を渡してやることができます。
私がまだまだAngularに慣れていないからかわかりませんが、結構時間がかかってしまいました。
ngx-color-pickerは他にも便利なオプションがあるので、ぜひ参考にしてみてください。

参考

ngx-color-picker
examples
How to Use Color Picker in Angular

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?