I've a class as shown below
export class Story {
id: number;
title: string;
storyText: string;
utcDate: string;
get displayDate(): string {
const today = new Date();
const postDate = new Date(this.utcDate);
const td = today.getTime();
const pd = postDate.getTime();
return ((td-pd)/1000)+'ms';
}
}
HTML view is shown below
<span>
<i class="fa fa-clock-o" aria-hidden="true"></i>
{{story.displayDate}}
</span>
Here, the html code block is inside and ngFor loop as *ngFor="let story of stories"
and stories is an array of type Story , stories: Story[];
But its not displaying anything . No error also. What am I doing wrong here? Will this work like this without an explicit setter property? Or should I create a setter property and set the value manually?
edit: below my script that populate the story array and the service function
loadData() {
this.storyService.stories()
.subscribe(
data => {
const response = <Story[]>data.message;
this.stories = response;
},
error => {
alert('error');
});
}
stories() {
return this.http.get<Result>(this.baseUrl + '/story/list/', this.httpOptions);
}
Your getter wont work unless you create a new instance. Also when you are putting stories: Story[], you are only telling that it is safe to assume Stories will contain properties in Story class. Typescript wont that there is a getter.
Since you are inside ngFor, I suggest using a Pipe.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'displayDate'
})
export class DisplayDatePipe implements PipeTransform {
transform(value: any): string {
const today = new Date();
const postDate = new Date(value);
const td = today.getTime();
const pd = postDate.getTime();
return ((td-pd)/1000).toString();
}
}
then in your template make slight modification like this.
<span>
<i class="fa fa-clock-o" aria-hidden="true"></i>
{{story.utcDate | displayDate }}
</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With