詳細ガイド
ディレクティブ

組み込みディレクティブ

ディレクティブは、Angularアプリケーションの要素に追加の動作を追加するクラスです。

Angularの組み込みディレクティブを使用して、フォームやリスト、スタイルおよびユーザーに見えるものを管理します。

Angularディレクティブの種類は以下のとおりです。

ディレクティブの種類 詳細
コンポーネント テンプレートで使用されます。このタイプのディレクティブは、最も一般的なディレクティブタイプです。
属性ディレクティブ 要素、コンポーネント、または他のディレクティブの外観や動作を変更します。
構造ディレクティブ DOM要素を追加または削除することによって、DOMレイアウトを変更します。

このガイドでは、組み込みの 属性ディレクティブを取り上げます。

組み込み属性ディレクティブ

属性ディレクティブは、他のHTML要素、属性、プロパティ、およびコンポーネントの動作を監視して変更します。

最も一般的な属性ディレクティブは以下のとおりです。

一般的なディレクティブ 詳細
NgClass CSS クラスのセットを追加および削除します。
NgStyle HTML スタイルのセットを追加および削除します。
NgModel HTML フォーム要素に双方向データバインディングを追加します。

HELPFUL: 組み込みディレクティブは、公開APIのみを使用します。他のディレクティブがアクセスできないプライベートAPIには、特別なアクセス権がありません。

NgClass を使用してクラスを追加および削除する

ngClass を使用して、複数のCSSクラスを同時に追加または削除します。

HELPFUL: 単一の クラスを追加または削除するには、NgClass ではなく クラスバインディング を使用します。

コンポーネントに NgClass をインポートする

NgClass を使用するには、コンポーネントの imports リストに追加します。

app.component.ts (NgClass インポート)

import {NgClass} from '@angular/common';/* . . . */@Component({    /* . . . */    NgClass, // <-- import into the component    /* . . . */  ],})export class AppComponent implements OnInit {  /* . . . */}

式を使用して NgClass を使用

スタイルを設定する要素に、[ngClass] を追加して、式に等しく設定します。 この場合、isSpecial はブール値であり、app.component.tstrue に設定されています。 isSpecial がtrueのため、ngClass<div>special というクラスを適用します。

app.component.html

<!-- toggle the "special" class on/off with a property --><div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>

メソッドを使用して NgClass を使用

  1. メソッドを使用して NgClass を使用するには、メソッドをコンポーネントクラスに追加します。 次の例では、setCurrentClasses() は3つの他のコンポーネントプロパティの true または false 状態に基づいて、3つのクラスを追加または削除するオブジェクトを使用してcurrentClasses プロパティを設定します。

    オブジェクトの各キーは、CSSクラス名です。 キーが true の場合、ngClass はクラスを追加します。 キーが false の場合、ngClass はクラスを削除します。

    app.component.ts

    currentClasses: Record<string, boolean> = {};  /* . . . */  setCurrentClasses() {    // CSS classes: added/removed per current state of component properties    this.currentClasses = {      saveable: this.canSave,      modified: !this.isUnchanged,      special: this.isSpecial,    };  }
  2. テンプレートで、要素のクラスを設定するために、currentClasses に対する ngClass プロパティバインディングを追加します。

    app.component.html

    <div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>

このユースケースでは、Angularは初期化時に、および currentClasses オブジェクトの再代入によって発生した変更が発生した場合に、クラスを適用します。 完全な例では、ユーザーが Refresh currentClasses ボタンをクリックしたときに、ngOnInit() を使用して最初に setCurrentClasses() を呼び出します。 これらの手順は、ngClass を実装するために必要ではありません。

NgStyle を使用してインラインスタイルを設定する

HELPFUL: To add or remove a single style, use style bindings rather than NgStyle.

コンポーネントに NgStyle をインポートする

NgStyle を使用するには、コンポーネントの imports リストに追加します。

app.component.ts (NgStyle インポート)

import {NgStyle} from '@angular/common';/* . . . */@Component({    /* . . . */    NgStyle, // <-- import into the component    /* . . . */  ],})export class AppComponent implements OnInit {  /* . . . */}

NgStyle を使用して、コンポーネントの状態に基づいて、複数のインラインスタイルを同時に設定します。

  1. NgStyle を使用するには、コンポーネントクラスにメソッドを追加します。

    次の例では、setCurrentStyles() は3つの他のコンポーネントプロパティの状態に基づいて、3つのスタイルを定義するオブジェクトを使用して currentStyles プロパティを設定します。

    app.component.ts

    currentStyles: Record<string, string> = {};  /* . . . */  setCurrentStyles() {    // CSS styles: set per current state of component properties    this.currentStyles = {      'font-style': this.canSave ? 'italic' : 'normal',      'font-weight': !this.isUnchanged ? 'bold' : 'normal',      'font-size': this.isSpecial ? '24px' : '12px',    };  }
  2. 要素のスタイルを設定するには、currentStyles に対する ngStyle プロパティバインディングを追加します。

    app.component.html

    <div [ngStyle]="currentStyles">  This div is initially italic, normal weight, and extra large (24px).</div>

このユースケースでは、Angularは初期化時と、変更が発生した場合にスタイルを適用します。 これを行うために、完全な例では、ngOnInit() を使用して最初に setCurrentStyles() を呼び出し、依存プロパティがボタンクリックを通じて変更されたときに呼び出します。 ただし、これらの手順は、ngStyle 自体を実装するために必要ではありません。

DOM 要素のないディレクティブをホストする

Angularの <ng-container> は、AngularがDOMに配置しないため、スタイルやレイアウトに影響を与えないグループ化要素です。

ディレクティブをホストする単一の要素がない場合は、<ng-container> を使用します。

以下は、<ng-container> を使用した条件付きのパラグラフです。

app.component.html (ngif-ngcontainer)

<p>  I turned the corner  <ng-container *ngIf="hero"> and saw {{hero.name}}. I waved </ng-container>  and continued on my way.</p>
適切なスタイルが適用された ngcontainer パラグラフ
  1. FormsModule から ngModel ディレクティブをインポートします。

  2. FormsModule を、関連するAngularモジュールのインポートセクションに追加します。

  3. <option> を条件付きで除外するには、<option><ng-container> でラップします。

    app.component.html (select-ngcontainer)

    <div>  Pick your favorite hero (<label for="showSad"    ><input id="showSad" type="checkbox" checked (change)="showSad = !showSad" />show sad</label  >)</div><select [(ngModel)]="hero">  <ng-container *ngFor="let h of heroes">    <ng-container *ngIf="showSad || h.emotion !== 'sad'">      <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>    </ng-container>  </ng-container></select>
    ngcontainer オプションは正しく機能します

次のステップ