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:
JavaScript
x
4
1
<span id="date-time">
2
{{getCurrentDateTime()}}
3
</span>
4
Method in the typescript file:
JavaScript
1
8
1
// This method returns the current date-time of a timezone
2
public getDateTimeForSiteDifferentTimeZone(): string {
3
const momentString = moment.tz(this.timeZone).format('DD MMM y, hh:mm A');
4
return momentString;
5
}
6
return '';
7
}
8
Advertisement
Answer
You could do this:
- In your template, declare a variable
time
:
JavaScript
1
5
1
export class SomeComponent implements OnInit {
2
time = getCurrentDateTime()
3
4
}
5
- Interpolate
time
JavaScript
1
4
1
<span id="date-time">
2
{{time}}
3
</span>
4
- Create an
ngOnInit
function and fill it with asetInterval
for 60000ms (1 minute, because your time seems to display only minute). when it fires, update thetime
variable.
JavaScript
1
4
1
ngOnInit() {
2
setInterval(() => {time = getCurrentDateTime()}, 60000)
3
}
4