カスタムAngularディレクティブで@HostBindingと@HostListenerを使用する方法

提供:Dev Guides
移動先:案内検索

序章

@HostBinding@HostListenerは、カスタムディレクティブで非常に役立つAngularの2つのデコレータです。 @HostBindingを使用すると、ディレクティブをホストする要素またはコンポーネントにプロパティを設定でき、@HostListenerを使用すると、ホスト要素またはコンポーネントのイベントをリッスンできます。

この記事では、ホスト上のkeydownイベントをリッスンするディレクティブの例で、@HostBindingおよび@HostListenerを使用します。

テキストと境界線の色を、使用可能ないくつかの色のセットからランダムな色に設定します。

前提条件

このチュートリアルを完了するには、次のものが必要です。

このチュートリアルは、ノードv16.4.2、npm v7.18.1、angularv12.1.1で検証されました。

@HostBindingおよび@HostListenerを使用する

まず、新しいRainbowDirectiveを作成します。

これは、@angular/cliで実現できます。

ng generate directive rainbow --skip-tests

これにより、新しいコンポーネントがアプリdeclarationsに追加され、rainbow.directive.tsファイルが生成されます。

src / app / rainbow.directive.ts

import { Directive } from '@angular/core';

@Directive({
  selector: '[appRainbow]'
})
export class RainbowDirective {

  constructor() { }

}

@HostBinding@HostListenerを追加します。

src / app / rainbow.directive.ts

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];
  }

}

また、ディレクティブは次のような要素で使用できます。

src / app / app.component.html

<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は、ホストでキーダウンイベントをリッスンします。 colorborderColorの値を変更するこのデコレータにアタッチされた関数を定義すると、変更はホストに自動的に反映されます。

結論

この記事では、ホスト上のkeydownイベントをリッスンするディレクティブの例で、@HostBindingおよび@HostListenerを使用しました。

Angularについて詳しく知りたい場合は、Angularトピックページで演習とプログラミングプロジェクトを確認してください。