LoginSignup
3
0

More than 1 year has passed since last update.

1. はじめに

 スターアプリケーションズ株式会社の吉田です。
 みなさん、strict:true やっていますか。はい、コンパイルエラーの修復ご苦労様です。TypeScriptの型チェック厳密になって大変ですね。今回、変数のnull/undefinedチェックで、AngularのNullish Coalescingを使うと、便利になるので記事にしました。

2. 復習

 Nullish Coalescingですが、JavaScript、TypeScriptには、以前より実装済みの機能です。AngularではV12から AngularのTemplateで使用することができるようになりました。Mark Thompson氏のブログ、(Angular v12 is now available)から例を見ていきましょう。

{{age !== null && age !== undefined ? age : calculateAge() }}

上記は以下のように置き換えられます。

{{ age ?? calculateAge() }}

??の左側:nullでもundefinedでもない時の表示
??の右側:null又はundefinedの時表示される値

3. デモプログラム

  デモと言っても、大したものではありません。主な作成部分は次の2ヶ所です。

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'NullishCoalescing';

  prefecture ?: string  ;
  city : string | null = null;
  street ?: string ;
}
app.component.html
<h2> Nullish Coalescing DEMO</h2>
<div>
  都道府県:<input  type="text" [(ngModel)]="prefecture">
</div>
<div>
  市区町村:<input  type="text" [(ngModel)]="city">
</div>
<div>
  町名番地:<input  type="text" [(ngModel)]="street">
</div>
<br>
<h3>住所</h3>
<span>
    {{ prefecture ?? "**都道府県名入力なし** "}}
</span>
<span>
    {{ city ?? "**市区町村名入力なし** "}}
</span>
<span>
    {{ street ?? "**町名番地名入力なし** "}}
</span>

プログラム全体を見る

参考

Angularでstrict: trueにした。(strictNullChecks, strictPropertyInitialization編)

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