Angular-TUTORIALのngIf見て?がでてきたので、if文とクラス変数の比較の再確認をしてみた
URLはここ→https://angular.io/docs/ts/latest/tutorial/toh-pt2.html
1行目にあるselectedHerosはHeroクラスの変数で宣言されている。
これはselectedHerosがnullまたはundefineの場合は後続の処理を行わないようにしている。
※試しにifの行を削除するとselectedHero.nameが未定義でエラーが発生する。
1 2 3 4 5 6 7 8 |
<div *ngIf="selectedHero"> <h2>{{selectedHero.name}} details!</h2> <div><label>id: </label>{{selectedHero.id}}</div> <div> <label>name: </label> <input [(ngModel)]="selectedHero.name" placeholder="name"/> </div> </div> |
変数宣言時の状態によるif文の判定
取り敢えず動かしてみた結果こんな感じ。AngularではTypeScriptで型宣言を行うためオブジェクトがnullかundefinedならif(変数)
で十分だろう
変数名 | 初期化 | if判定 |
---|---|---|
noInitial | なし | false |
nullObject | null | false |
undefineObject | undefined | false |
anyObject | あり | true |
ソース
1 2 3 4 5 6 7 8 9 10 11 |
let noInitial: any; const nullObject: any = null; const undefineObject: any = undefined; const anyObject: any = new Object(); console.log('noInitial typeof', typeof noInitial); console.log('noInitial', noInitial === null ? 'null' : 'not null'); console.log('noInitial', noInitial === undefined ? 'undefined' : 'not undefined'); console.log('noInitial', noInitial ? true : false); console.log('nullObject', nullObject ? true : false); console.log('undefineObject', undefineObject ? true : false); console.log('anyObject', anyObject ? true : false); |
実行結果
1 2 3 4 5 6 7 |
noInitial typeof undefined noInitial not null noInitial undefined noInitial false nullObject false undefineObject false anyObject true |