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タグは表示されます。
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にすると、以下のように表示されます。
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を作成する」を参照ください。
KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^
コメント