The Angular template is throwing an error stating that c_r1.getCatType is not a valid function

Within my Angular project (version 9.1.0), I have a class structured like this:

export class Contract {
    contractName: string;
    limit: number;
    public getCatType(): string{
       if(this.limit > 0) return 'p';  
       return 'n';  // simplified for brevity
    }
}

I've incorporated this class in the template as follows:

<tr *ngFor="let c of contracts">          
          <td>{{c.contractName}}</td>
          <td>{{c.limit | number}}</td>
          <td>{{c.getCatType()}}</td>
      </tr>

However, during runtime, the template raises an error stating c_r1.getCatType is not a function.

Upon investigation, I realized that the issue stemmed from the fact that "contracts" was populated by an API call result:

this.cService.getList(pId).subscribe((contracts: Contract[]) => {
        this.contracts = contracts;   // Suspected line causing the issue
    }, (err) => {...});

Does anyone have insights on how to resolve this?

Check out a demo showcasing this error:

Thank you in advance.

Answer №1

It's not recommended to use methods in a template within Angular, as they can be called multiple times during change detection cycles.

Instead of using a method directly, consider creating a custom pipe with the desired logic and applying it to the data.

If 'c' does not have a method associated with it, make sure to pass the necessary parameter and return the desired result using this approach:

<td>{{getCatType(c)}}</td>

Verify where the limit is being set, although it may not affect how getCatType is invoked within the template.

For more information on pipes, you can refer to this resource.

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 type of 'data' is assumed to be 'any[]' without being explicitly stated

I am encountering several type errors in the function below, and as a newcomer to Typescript, I'm unsure about how to fix them. private fetchFromUrl = () => { var data = [] fetch(`${process.env.PUBLIC_URL}/tempData/monthly.csv`) .t ...

Exploring ways to ensure robust typing for the body of NextApiRequest within a Next.js environment

Are you trying to figure out how to correctly define the body type of an API POST route in Next.js for better type safety? In NextApiRequest, the body is currently defined as "any" and NextApiRequest itself is not generic. I have tried forcefully assigni ...

Determine rest parameters based on the initial argument

Struggling to generate a solution that infers the arguments for an ErrorMessage based on the provided code input. ./errorCodes.ts export enum ErrorCodes { ErrorCode1, ErrorCode2, ErrorCode3 } ./errorMessages.ts export const ErrorMessages = { [Err ...

I'm curious, where does Visual Studio create the dist folder when you run an Angular Web Application?

Currently utilizing Visual Studio 2019 Community Edition, although the same situation also pertains to VS2017 and other editions of 2017/2019. While developing/running an ASP.NET Core Web Application with an Angular web project, I'm unable to locate ...

Utilizing Angular's Dynamic Component Import and Loading capabilities

Looking to develop a portal that can dynamically load Angular components without the need for explicit imports. I've heard about using ComponentFactoryResolver for this purpose, but hoping to have the ability to store components in separate files or r ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:AngularhttpErrorHandlingExamplesrcapp'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: E ...

What is the best way to store a logged-in user's email in a React

I have implemented a login API and I would like to save the email of the logged-in user in the state or another variable, so that I can display it in the header after successful login. The user's email is located in the data.email. The following code ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

Access the most up-to-date information through the API URL

Objective: Whenever the 'Test' Button is clicked, new data must be fetched from the backend using the API link and displayed on the modal form. Issue: If text in the input box is changed or deleted, then the modal is closed and the 'Tes ...

The feature of Nuxt 3's tsconfig path seems to be malfunctioning when accessed from the

Take a look at my file structure below -shared --foo.ts -web-ui (nuxt project) --pages --index.vue --index.ts --tsconfig.json This is the tsconfig for my nuxt setup. { // https://v3.nuxtjs.org/concepts/typescript "exte ...

Enabling the "allowUnreachableCode" Compiler Option in Visual Studio 2015 Triggers "JsErrorScriptException (0x3001)" Issue

We've implemented TypeScript in our Visual Studio 2015 (Update 2) setup for a non-ASP.Net project consisting of pure HTML and JavaScript. In order to disable the 'allowUnreachableCode' option, we made adjustments in the tsconfig file. It&apo ...

What is the best way to implement a Promise Function within a For loop?

Here is a function called sendEmail: public async sendEmail (log: LogMessage): Promise<void> { nodemailer.createTestAccount(async () => { return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => ...

What is the best way to simulate a dynamoDB call using jest?

In a simple Handler, I have calls to getData defined in a separate file export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => { let respData = await new DynamoDBClient().getData(123); return { status ...

Charging for Firebase together with Server-Side Rendering

Utilizing a simplistic Cloud Function to ascertain whether the incoming request is bot-generated, I then deliver server-rendered content if that criterion is met on an Angular application hosted via Firebase. My understanding leads me to believe that this ...

Angular 4 - Issues with route configurations

My Angular application is running smoothly on localhost:4200 using ng serve. The node server can be found at localhost:3000. After running ng build, a bundle file is generated and properly served from localhost:3000 thanks to the line app.use(express.sta ...

Obtain unique entries from a Firestore collection search

Seeking assistance in filtering an observable to only contain unique records. I am using the observable in an angular mat-autocomplete with an async pipe and querying firebase based on the user's input. The code for the mat-autocomplete template: ...

Guide to personalizing NbLayoutComponent through the creation of a new class extension

Is there a way to make the footer full screen width instead of just the contents section in my app? I am using Nebular for building it. I have tried creating a custom component by extending nbLayoutComponent, but I'm not sure if this is the correct a ...

Setting innerHTML does not affect the content of an SVG element

I am currently working on an Angular 7 application and I need to dynamically update the text value based on a dropdown selection. For example, if the id of the text element is 10, then I want to change the text from 'hi' to 'hello'. T ...

Updating templates using Angular 2 observables for change detection

Looking to optimize performance, I am exploring the implementation of manual change detection on my components. The app structure is as follows: App -> Book(s) -> Page(s) In the AppComponent, I subscribe to an observable and then utilize the "markF ...