Angular のngIf ディレクティブの使い方

Angular のngIf ディレクティブの使い方

AngularにはngIfディレクティブというディレクティブが標準で用意されています。

単なるif文で使い方としてはif文がtrueの場合に表示するといった機能です。

記述方法は以下のような感じで記述します。

dell.component.html

<div *ngIf='flg'>
  <p>{{flg}}</p>
</div>

dell.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-dell',
templateUrl: './dell.component.html',
styleUrls: ['./dell.component.css']
})
export class DellComponent implements OnInit {

constructor() { }
flg = true;
ngOnInit() {
}
}

flg = true;なのでdivタグは表示されます。

Angular のngIf ディレクティブの使い方

Angular4以降はngIf~else文が記述できます。

dell.component.html

<div *ngIf='flg; else Statement'> <!-- 囲っている範囲に注意 -->
  <p>{{flg}}</p>
</div>
<ng-template #Statement>
  <p>else文です</p>
</ng-template>

flgをfalseにすると、以下のように表示されます。

Angular のngIf ディレクティブの使い方

boolean型でない場合の挙動

ngIf='変数'の変数の部分はboolean型であるとは限りません。

falseの挙動になる場合を調べました。

結果
true true
false false
null false
undefined false
[] true
{} true
0 false
1 true
-1 true

ngIfを使用するには、app.module.tsで、以下をimportしておく必要があります。

import { FormsModule } from '@angular/forms';

imports [
  BrowserModule,
  FormsModule
]

詳細は「AngularとTypeScriptでSPAを作成する」を参照ください。

コメント

株式会社CONFRAGE ITソリューション事業部をもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む

タイトルとURLをコピーしました