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