Search code examples
javascripthtmlangularangular-template

How can I display date and time in Angular template and keep it updated?


I need to display date and time in my angular template, and keep it updated, so when time is changed to show changed time ofcourse, application SHOULD look like this:

this is my .html template code:

<div class="top-right pull-right">
  <button type="button" class="btn xbutton-rectangle" (click)="logOut()">
    <div class="icon-user pull-left">
      <i class="fas fa-user fa-fw"></i>
      <span class="button-text">{{employee.FullName}}</span>
    </div>
    <div class="time-date pull-right">
      <p class="button-time">08:55</p>
      <p class="button-date">22.06.2018</p>
    </div>
  </button>
</div>

My .ts file:

@Component({
  selector: 'main-screen',
  templateUrl: './main-screen.component.html',
  styleUrls: ['./main-screen.component.css']
})
export class MainScreenComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
    //.. some methods 
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  logOut() {
    this._globals.isAuthenticated = false;
    this._globals.loggedInUser = null;
    this._globals.token = null;
  }

} 

So how can I display date and time? and keep it updated when system date&time changes?


Solution

  • All you need to do is use the setInterval on your constructor

      date:Date; 
      constructor(){
        setInterval(() => {
          this.date = new Date()
        }, 1000)
      }
    

    And use the date pipe to format the date and time

    {{date   | date: "MM-dd-yyyy"}}
    {{date   | date: "HH:mm:ss"}}
    

    Demo