Troubleshooting: Issues with accessing Angular/Typescript Class Getter property

I have a class defined as follows:

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';
    }
}

The HTML view is as shown below:

<span>
   <i class="fa fa-clock-o" aria-hidden="true"></i>
   {{story.displayDate}}
</span>

In this case, the html code block is inside an ngFor loop like *ngFor="let story of stories", where "stories" is an array of type "Story" - stories: Story[]; However, nothing is being displayed. There are no errors either. What could be wrong? Can it work without an explicit setter property? Should I create a setter property and set the value manually?

Edit: Below is my script that populates 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);

 }

Answer №1

If you want your getter to work properly, it's important to create a new instance. Additionally, when specifying stories as Story[], you are essentially indicating that Stories will contain properties from the Story class. TypeScript won't automatically detect the presence of a getter.

When working inside ngFor, utilizing a Pipe is recommended.

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();
  }

}

To make this work in your template, adjust it like so:

<span>
   <i class="fa fa-clock-o" aria-hidden="true"></i>
   {{story.utcDate | displayDate }}
</span>

Answer №2

The reason behind this issue is that when casting in Typescript, the methods are not included. Consider the following scenario:

const data = {
    id: 1,
    title: 'foo',
    storyText: 'bar',
    utcDate: '01-01-2000'
}

const story = data as Story;
// OR
const story = <Story> data;

console.log( story.displayDate ); // This will be incorrect because the method is missing

Instead of trying to access the method directly, you should create a new object:

const story = new Story(data.id, data.title, data.storyText, data.utcDate);
console.log( story.displayDate ); // This approach will work!

However, keep in mind that this requires having a constructor, and also potentially looping through an array of stories.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The pathway specified is untraceable by the gulp system

Hey there, I've encountered an issue with my project that uses gulp. The gulpfile.js suddenly stopped working without any changes made to it. The output I'm getting is: cmd.exe /c gulp --tasks-simple The system cannot find the path specified. ...

Flipping the Observable List in Angularfire2

Currently, I have implemented the following code to reverse the list: this.items = this.db.list('/privacy').map( (array) => {return array.reverse()} ) as FirebaseListObservable<any[]>; When displaying the list, I call it like this: &l ...

Oops! An issue occurred during the `ng build` command, indicating a ReferenceError with the message "Buffer is not defined

I'm facing an issue while trying to utilize Buffer in my angular component ts for encoding the Authorization string. Even after attempting npm i @types/node and adding "node" to types field in tsconfig.json, it still doesn't compile with ng buil ...

Steps for developing a versatile function Component

Can I create generic function components? I thought that the following example would work: type MyComponentProps<T> = T & { component: ComponentType<T>, primary?: boolean, size?: 'S' | 'M' | 'L' ...

Encountered an error while attempting to install the DataTables npm package in an Angular

I am trying to add datatables to my angular application. Upon running ng add angular-datatables An error code is displayed (refer to the image). error image The cause of this error is unknown to me. Please review the package.json file as well. package.j ...

Accessing nested JSON objects with key-value pairs

I have a method in my .ts file that displays keys but doesn't fetch nested JSON data. generateArr(obj) { return Object.keys(obj).map((key) => { console.log(key, obj[key]); return {key: key, value: obj[key]}; }); } Here is the HTML code I&apo ...

How can we optimize component loading in react-virtualized using asynchronous methods?

In my component, I have implemented a react-virtualized masonry grid like this: const MasonrySubmissionRender = (media: InputProps) => { function cellRenderer({ index, key, parent, style }: MasonryCellProps) { //const size = (media.submiss ...

Resolve the conflict with the upstream dependency in Angular

I understand that the solution to this issue can be found on SOF, but utilizing --legacy-peer-deps or --force is not an option for me on my production server. I am eager to comprehend the root cause of this error and find a proper resolution. Upon install ...

Steps for altering the primary color in PrimeNG__Changing the primary color

What is the most effective way to modify the default primary color for primeNG (saga-blue theme)? Altering --primary-color does not have the desired effect, as elements in node_modules/..../theme.css are styled using the main color hex rather than '-- ...

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

Dynamic placeholder modification depending on form selection

How can I dynamically change the placeholder text based on user selection? //div with a toggle for two options <div fd-form-item> <label fd-form-label for="select-targetType">Showroom type:</label> <select class=&q ...

Can Angular reactive forms be used to validate based on external conditions?

Currently, I am exploring Angular reactive forms validation and facing an issue with implementing Google autocomplete in an input field: <input autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="input-auto input" formControlName ...

Original: Generic for type guard functionRewritten: Universal

I have successfully created a function that filters a list of two types into two separate lists of unique type using hardcoded types: interface TypeA { kind: 'typeA'; } interface TypeB { kind: 'typeB'; } filterMixedList(mixedList$: ...

There was an error encountered during the npm install process

C:\Users\Mayur Saner\pmrm>npm install npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! network request to http://registry.npmjs.org/@fortawesome%2ffontawesome-free failed, reason: getaddrinfo ENOTFOUND proxy.company.com npm ERR! ...

The Angular project encounters a failure when attempting to run 'ng serve,' resulting in an emitted 'error' event on the worker

Resolved Issue - Update: It appears that the problem was due to an error in my CSS code: Previous: .title & .smaller { color: $dark-blue; font-family: "Roboto"; font-size: 20px; font-weight: 600; width: fit-content; margin: 0; ...

Angular promise not triggering loop creation

I am encountering an issue with a particular function handleFileInput(file: any) { let promise = new Promise((resolve, reject) => { this.uploadFileDetails.push({ filename:this.FileName,filetype:this.FileType}); ... resolve(dat ...

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

Having difficulty accessing the 'makeCurrent' property of an undefined object in Angular mobile application

I have followed the steps outlined in the Angular mobile toolkit guide found at https://github.com/angular/mobile-toolkit/blob/master/guides/cli-setup.md My Node version is v4.4.3 NPM version is 2.15.1 The issue arises when I run the command $ ng serve, ...

What is the best way to convert a date to ISO 8601 format using JavaScript? Are there any built-in functions or methods in

Currently, I am using this function to set the duration: const setDuration = () => { const currentDate = new Date(); const newDate = new Date(currentDate.getTime()); const year = newDate.getUTCFullYear(); const m ...

Ways to identify if there is a problem with the Firestore connection

Can anyone help me understand how I can use angularfire2 to check the accessibility of the cloud firestore database and retrieve collection values? If accessing the cloud database fails, I want to be able to retrieve local data instead. This is an exampl ...