カスタムAngularディレクティブで@HostBindingと@HostListenerを使用する方法
序章
@HostBinding
と@HostListener
は、カスタムディレクティブで非常に役立つAngularの2つのデコレータです。 @HostBinding
を使用すると、ディレクティブをホストする要素またはコンポーネントにプロパティを設定でき、@HostListener
を使用すると、ホスト要素またはコンポーネントのイベントをリッスンできます。
この記事では、ホスト上のkeydown
イベントをリッスンするディレクティブの例で、@HostBinding
および@HostListener
を使用します。
テキストと境界線の色を、使用可能ないくつかの色のセットからランダムな色に設定します。
前提条件
このチュートリアルを完了するには、次のものが必要です。
- Node.jsはローカルにインストールされます。これは、Node.jsのインストール方法とローカル開発環境の作成に従って実行できます。
- AngularプロジェクトのセットアップおよびAngularコンポーネントの使用にある程度精通していると有益な場合があります。
このチュートリアルは、ノードv16.4.2、npm
v7.18.1、angular
v12.1.1で検証されました。
@HostBinding
および@HostListener
を使用する
まず、新しいRainbowDirective
を作成します。
これは、@angular/cli
で実現できます。
- ng generate directive rainbow --skip-tests
これにより、新しいコンポーネントがアプリdeclarations
に追加され、rainbow.directive.ts
ファイルが生成されます。
import { Directive } from '@angular/core';
@Directive({
selector: '[appRainbow]'
})
export class RainbowDirective {
constructor() { }
}
@HostBinding
と@HostListener
を追加します。
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appRainbow]'
})
export class RainbowDirective {
possibleColors = [
'darksalmon',
'hotpink',
'lightskyblue',
'goldenrod',
'peachpuff',
'mediumspringgreen',
'cornflowerblue',
'blanchedalmond',
'lightslategrey'
];
@HostBinding('style.color') color!: string;
@HostBinding('style.border-color') borderColor!: string;
@HostListener('keydown') newColor() {
const colorPick = Math.floor(Math.random() * this.possibleColors.length);
this.color = this.borderColor = this.possibleColors[colorPick];
}
}
また、ディレクティブは次のような要素で使用できます。
<input type="text" appRainbow />
Rainbow
ディレクティブは、2つの@HostBinding
デコレータを使用して、2つのクラスメンバーを定義します。1つはホストのstyle.color
バインディングに接続され、もう1つはstyle.border-color
に接続されます。
ホストの任意のクラス、プロパティ、または属性にバインドすることもできます。
可能なバインディングの例をさらにいくつか示します。
@HostBinding('class.active')
@HostBinding('disabled')
@HostBinding('attr.role')
'keydown'
引数を持つ@HostListener
は、ホストでキーダウンイベントをリッスンします。 color
とborderColor
の値を変更するこのデコレータにアタッチされた関数を定義すると、変更はホストに自動的に反映されます。
結論
この記事では、ホスト上のkeydown
イベントをリッスンするディレクティブの例で、@HostBinding
および@HostListener
を使用しました。
Angularについて詳しく知りたい場合は、Angularトピックページで演習とプログラミングプロジェクトを確認してください。