LoginSignup
0
0

More than 1 year has passed since last update.

三項演算子とパイプを使った実装方法

Posted at

はじめに

初心者向け。
条件式を簡単に書ける三項演算子と、値を変換するAngularの機能であるパイプを使った、文字数カウンタを例にして実装する。

実装結果

入力された文字数をカウントして表示する。
文字数が1000を超える場合は三桁カンマをつけ、文字が入力されていない場合は文字数の欄に「---」と表示する。
スクリーンショット 2023-01-01 11.32.40.pngスクリーンショット 2023-01-01 11.32.53.png

実装方法

app.component.html
<label for="text">入力された文字をカウントします。</label>
<textarea
  name="text"
  id="text"
  [(ngModel)]="text"
  (input)="changeTextArea()"
  cols="30"
  rows="10"
></textarea>
<h3 name="textCount">
  文字数: {{ textCount ? (textCount | number) : '---' }}
</h3>
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  text = '';
  textCount = 0;
  changeTextArea() {
    this.textCount = this.text.length;
  }
}

解説

今回の解説対象は上記で示した文字数表示のhtmlコードである。

<h3 name="textCount">
  文字数: {{ textCount ? (textCount | number) : '---' }}
</h3>

問題となるのは以下の部分。

textCount ? (textCount | number) : '---'

三項演算子として見ると、変数A ? 変数A : 文字列とシンプルに書ける。
これは変数Aの値があれば、変数Aを表示し、なければ文字列を表示するという意味だ。

今回の例では、変数Aの値があった場合、変数Aに| numberを付け加えることで、decimalpipeを使用し、三桁カンマ付加して表示している。
このとき、パイプの対象がわかるようにtextCount | numberに丸かっこをつけるのを忘れないようにする。

参考文献

以下は、実際動くコードのサンプル。

おわりに

三項演算子とパイプを使った実装方法を紹介した。他にも自分で三桁カンマをつけたり、ケースによってふさわしい実装方法は変わってくるが、実装方法の一つとして頭に入れておきたい。
丸かっこをつければパイプの実装ができたのに、という残念な結果にならないように記録に残す。

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