1

Please how can I refresh a date in angular 4

I need to display dynamically the date in the web page.

This is my code:

import { Component } from '@angular/core';

import * as moment from "moment";

 @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
 })
 export class AppComponent {
      title = 'My First Angular application';
      oneHourAgo: string = "";
      EightHoursAgo: string = "";
      constructor(  ) { 

  }

  curTime() {
         let now = moment().format("YYYY-MM-DD HH:mm:ss");
         return now;
  }    

}
Sarthak Aggarwal
  • 2,284
  • 1
  • 8
  • 12
sr123
  • 85
  • 1
  • 11

1 Answers1

1

Simply bind the result to the template like this:

export class AppComponent implements OnInit, OnDestroy {
  myTime
  myInterval
  title = 'My First Angular application';
  oneHourAgo: string = "";
  EightHoursAgo: string = "";
  constructor () {}

  // you may want to use ngOnInit to call curTime   
  ngOnInit() {
    this.curTime()
    this.myInterval = setInterval(() => {
      this.curTime()
    }, 1000)
  }

  // if using setInterval then be sure to clean up else it will keep
  // firing after the component is destroyed
  ngOnDestory() {
    clearInterval(this.myInterval)
  }

  curTime() {
     console.log('hello i am updating the displayed time')
     this.myTime = moment().format("YYYY-MM-DD HH:mm:ss");
  }
}

and in the HTML template for the component:

<div>{{ myTime }}</div>

Whatever you do make sure curTime() is being called. I presume you are calling it in the HTML.

danday74
  • 52,471
  • 49
  • 232
  • 283