2017-11-08 11 views
0

私は現在時刻を示すmoment.jsを使ってAngularコンポーネントを作ろうとしています。角度4動的にコンポーネントビューを更新しますか?

初期化時にngOnInit()を使用して現在の時刻を設定し、次にupdateTime()関数を使用してhtmlに表示されるtimeプロパティを更新します。

私はconsole.logを使って更新作業を計画通りに示していますが、更新された文字列を表示する方法はわかりません。現在、ngOnInit()の後には静的なままです。

この機能を適切に行うために必要なことを理解してください。

import { Component, OnInit } from '@angular/core'; 
import $ from 'jquery'; 

@Component({ 
    selector: 'app-time', 
    templateUrl: './time.component.html', 
    styleUrls: ['./time.component.css'] 
}) 

export class TimeComponent implements OnInit { 

    time: any; 

    constructor() { 

    } 

    ngOnInit() { 
    var moment = require('moment'); 
    this.time = moment().format('h:mm:ss a'); 
    this.updateTime(); 
    } 

    updateTime() { 
    var moment = require('moment'); 
    setInterval(function() { 
     var now = moment(); 
     this.time = now.format('h:mm:ss a'); 
     console.log(this.time); 
    }, 1000); 
    } 

} 
+3

はそうのようにそれを設定しました。代わりに 'setInterval(()=> {'矢印の構文構文を使用してください) –

+0

それはそれでした。 – sMk

答えて

1

これはsetInterval関数スコープで使用できません。あなたがthis`は、あなたが期待するものではありません `、` function`キーワードを使用している場合

setInterval(() => { 
    let now = moment(); 
    this.time = now.format('h:mm:ss a'); 
    console.log(this.time); 
}, 1000); 
関連する問題