One-way binding with variable updating once a second not working

Hi! I’m building an app where I’ve got a date variable which I update by setting it to the local date once a second with a setinterval function. However, when I try to show those changes with one-way data binding (

{{date}}

) the page only displays the first value that variable takes and the same happens when using the [innerHTML] property. I thought it could be an Angular 2 issue, but then I did the same thing on an Angular 2 project and it worked fine. Is there any workaround for this problem?

Thanks in advance
Ravazzi

Here’s my TS code:

import { Component } from ‘@angular/core’;
import { NgZone } from ‘@angular/core’;

import { NavController } from ‘ionic-angular’;

@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {

private date=5;

constructor(public navCtrl: NavController) {
setInterval(function(){ this.date = new Date();console.log(this.date);}, 1000);
}
}

Does the problem persist if you ditch setInterval and use Observable.interval instead?

@rapropos It worked! Thanks! Here’s the code just in case someone comes to this post with the same issue I had:

import { Component } from ‘@angular/core’;

import { NavController } from ‘ionic-angular’;
import {Observable} from “rxjs”;

import * as moment from ‘moment’;

@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {

private date = moment();
private subscription;

constructor(public navCtrl: NavController) {
var source = Observable.interval(1000);

this.subscription = source.subscribe((x)=>this.date = moment());

}
}

Or you could write:

private date;

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

so that “this.date” refers to your class property “date” and not to the scope of your anonymous function(){}.