Skip to content
Advertisement

Angular template interpolation

Angular version 11

I have a template which uses a method of the typescript file which returns the current date time.

The thing is that if in the interpolation of the template I call this method, the first time I render the page, it works properly, but after 1 minute, the value should change to the next minute… which it does not….

How can I make that angular refreshes the template if the result of this method is different ?

template:

<span id="date-time">
   {{getCurrentDateTime()}}
</span>

Method in the typescript file:

// This method returns the current date-time of a timezone
public getDateTimeForSiteDifferentTimeZone(): string {
    const momentString = moment.tz(this.timeZone).format('DD MMM y, hh:mm A');
    return momentString;
  }
  return '';
}

Advertisement

Answer

You could do this:

  1. In your template, declare a variable time:
export class SomeComponent implements OnInit {
  time = getCurrentDateTime()
...
}
  1. Interpolate time
<span id="date-time">
   {{time}}
</span>
  1. Create an ngOnInit function and fill it with a setInterval for 60000ms (1 minute, because your time seems to display only minute). when it fires, update the time variable.
ngOnInit() {
  setInterval(() => {time = getCurrentDateTime()}, 60000)
}
Advertisement