0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Angular 構造ディレクティブについて

Last updated at Posted at 2025-04-06

Angularの構造ディレクティブとは

Angular の構造ディレクティブは、HTML の構造を変更するためのディレクティブである。要素を追加・削除したり、条件に応じて表示を切り替えたりする際に使われる。

構造はHTMLの構造のことで、そのHTMLの構造に対してディレクティブ(命令、変更)するということ。

代表的な構造ディレクティブ

ディレクティブ 説明
*ngIf 条件が true のときだけ要素を表示する
*ngFor リストなどの配列を繰り返して要素を表示する
*ngSwitch 複数のケースに応じて要素を切り替える

使用例

  • *ngIf
<div *ngIf="isLoggedIn">ようこそ!</div>

isLoggedIn が true のときだけ表示される。

  • *ngFor
<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

items 配列の中身を繰り返してリストにする。
items = ['りんご', 'バナナ', 'みかん'] の場合、以下のようなコードとなる。

<ul>
  <li>りんご</li>
  <li>バナナ</li>
  <li>みかん</li>
</ul>
  • *ngSwitch
<div [ngSwitch]="fruit">
  <p *ngSwitchCase="'apple'">りんごです</p>
  <p *ngSwitchCase="'banana'">バナナです</p>
  <p *ngSwitchDefault>他の果物です</p>
</div>

fruit === 'apple' のとき "りんごです" が出力される。

補足:なぜ * を使うのか

* は「構造ディレクティブの糖衣構文(コードを見やすくする構文)」で、Angular が裏で <ng-template> に変換して扱っている。

たとえば

<div *ngIf="isVisible">Hello World!!</div>

は、実際にはこう変換される↓

<ng-template [ngIf]="isVisible">
  <div>Hello World!!</div>
</ng-template>

まとめ

  • 構造ディレクティブは HTML 構造を制御する

  • *ngIf, *ngFor, *ngSwitch が代表例

  • *は裏でテンプレート構文を生成している

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?