LoginSignup
10
3

More than 5 years have passed since last update.

【Angular】小ネタ:現在時刻の表示

Posted at

はじめに

現在時刻を表示するサンプルソースがなかなか見つからなかったので。
こんな感じでやってますという小ネタです。
イメージはこんな感じです。
ezgif.com-video-to-gif.gif

コンポーネント側

ソース

app.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
  now: Observable<Date>;
  intervalList = [];

  constructor() {
  }

  public ngOnInit() {
    this.now = new Observable((observer) => {
      this.intervalList.push(setInterval(() => {
        observer.next(new Date());
      }, 1000));
    });
  }

  ngOnDestroy() {
    if (this.intervalList) {
      this.intervalList.forEach((interval) => {
        clearInterval(interval);
      });
    }
  }
}

やってること

  • observerに毎1秒毎に新たなDateを渡す
  • interval IDを保持しておく
  • ngOnDestroy時にclearIntervalでリセットしておく

clearIntevalしないと、たとえページ遷移してもずっと呼び出されるのでそこだけ注意です。
intervalIDの保持はリストである必要はありません。
ただ、複数の場所で使用するとその分保持すべきIDが増えるので、リストを使用しています。

html側

ソース

app.component.html
{{ now | async | date:'yyyy年MM月dd日 HH:mm:ss' }}

やってること

  • AsyncPipeを使ってDateを受け取る
  • 受け取ったDateを、DatePipeに流してフォーマットする

これだけです。

終わりに

これで現在時刻のリアルタイム表示が出来ます。
もっとシンプルな方法や、間違いの指摘等あればコメントよろしくお願いします。

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