How can I send a specific property of an object to a function in Angular?

I currently have a interface set up for employees that looks like this:

export interface IEmployee {
    name: string;
    id: number;
    annualSalary: number;
    calculateMonthlySalary(annualSalary: number): number;
}

Now, I have a component that is implementing the above interface:

import { Component, OnInit } from '@angular/core';
import { IEmployee } from './../employee';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit, IEmployee {

  employees: IEmployee[];

  constructor() {
    this.employees = [
      {name: 'john', id: 1, annualSalary: 90000, calculateMonthlySalary: this.calculateMonthlySalary(annualSalary) }
    ];
  }

  calculateMonthlySalary(annualSalary: number): any {
    return annualSalary / 12;
  }

}

While trying to compute the monthly salary using the calculateMonthlySalary method from the interface and displaying it in the view using *ngFor, I encountered the following error:

ERROR ReferenceError: annualSalary is not defined

Please help correct me where I might be going wrong

Answer №1

Consider trying the following approach:

See Working Demo 1 Here

this.employees = [
  {name: 'john', id: 1, annualSalary: 90000, calculateMonthlySalary: this.calculateMonthlySalary(90000) }
];

When adding objects of Type IEmployee to the array, the object itself doesn't understand annualSalary, so it should be added in the calculateMonthlySalary() function

To make it more dynamic, you can create an Employee Class:

Check out Working Demo 2 Here

export class Employee {
  name: string;
  id: number;
  annualSalary: number;
  monthlySalary:number
  constructor(name: string, id: number, annualSalary: number) {
    this.name = name,
    this.id = id,
    this.annualSalary = annualSalary,
    this.monthlySalary = this.calculateMonthlySalary(annualSalary)

 }

 calculateMonthlySalary(annualSalary: number): any {
    return annualSalary / 12;
 }
}

and use it like this:

employees: Employee[];

  constructor() {
    this.employees = [
      new Employee('John',1,90000)
    ];
  }

Template:

<table>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>MonthlySalary</th>
    </tr>
    <tr *ngFor="let item of employees">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.monthlySalary}}</td>
    </tr>
</table>

Answer №2

The reason is that annualSalary functions as a key rather than a value within this specific object.

Consider implementing the following solution:

const salary = 9000;
this.people = [
      {name: 'john', id: 1, annualSalary: salary, calculateMonthlyIncome: this.calculateMonthlyIncome(salary) }
    ];

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

HTML/Angular tutorial: Sharing an On-Click value with a different HTML element within the same component

As a newcomer to this, I could really use some guidance. Currently, I have a Mat Table that is displaying a specific range of data from my firestore. My goal is to be able to click on a particular row and have its data appear in a list below the table. I ...

Bring in the SCSS directory from the overarching SCSS program

I am currently working with Angular (Jhipster) in my application and I am looking to include multiple .scss files in my global.scss file. To achieve this, I have created a folder called "util" at the same level as the global.scss file and placed these .scs ...

Standardize API response using NgRX Entity

Can the NgRx Entity library normalize a nested JSON api response? If I have data structured like this: [ { "id": "1", "title": "My first post!", "author": { "id": "123", "name": "Paul" }, ...

tsc will automatically incorporate additional files

I'm grappling with a frustrating issue related to tsc that's really getting to me. The problem involves having a file b.ts in the src folder, and another file a.ts in the project root folder. Here is an excerpt of my tsconfig file: { "comp ...

Typescript offers a feature where we can return the proper type from a generic function that is constrained by a lookup type,

Imagine we have the following function implementation: type Action = 'GREET' |'ASK' function getUnion<T extends Action>(action: T) { switch (action) { case 'GREET': return {hello: &a ...

Avoid unwanted typeof warnings in TypeScript and WebStorm combination

How can I handle unwanted TypeScript checks related to JavaScript usage in today's development environment? Consider the following function: function connect(config: string): void { // Getting warning for the line that follows: // typeof ...

Incorporating CSS classes conditionally in an Angular child component using input values

I am currently using a list component: <section class="p-10 flex flex-col gap-10"> <p class="text-xl font-black text-blue-700">Transfer history</p> <div class="flex flex-col gap-10"> @for(item o ...

There was an error in parsing the module: an unexpected token was encountered during the rendering

Recently, I've been working on configuring React with Typescript (for type checking), Babel for code transpilation, Jest for testing, ESLint for code checking, and a few other tools. You can find all the necessary files in the repository linked below. ...

I'm having trouble locating a declaration file for the module 'vue-prism-component'

Currently utilizing Vue 3 (Composition API), Vite, and Typescript but encountering a missing module issue with vue-prism-component. <script lang="ts" setup> import 'prismjs' import 'prismjs/themes/prism-tomorrow.css' imp ...

Angular. The MatSelectionListChange event is returning an undefined value

I am attempting to retrieve the value of a changed element in a list, but I always get an undefined value while the checked property seems to be correct. HTML <div> <mat-selection-list #costUnits [(ngModel)]="selectedCostUnits" ...

Error: The token 'export' in d3zoom is causing a syntax issue

I'm encountering issues with executing tests in Angular: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export {default as zoom} from "./zoom.js"; ...

Trouble displaying data from rest api in Angular Material's mat-table

I've been attempting to incorporate mat-table into my Angular 8 project, but I seem to be missing something. The data from my REST endpoint is showing up fine in the console output. Here's my admin.component.html file: <table mat-table [ ...

There are no markers or popups currently displayed on the map

Utilizing the ngx-leaflet plugin for leaflet, I have established the base layers and integrated a listener for the leafletMapReady event. Within my handler, I attempted to add both a marker and a customized popup. The handler code is displayed below: init ...

What type is the appropriate choice for this handler?

I´m struggling to select the right type for this particular function. It serves as an async handler for express js in a project that utilizes typescript and eslint for linting with specific rules. export function asyncHandler( handler: any ): (req: Requ ...

Generate a configuration file that allows for the reading and storage of modifications

Is there a way to create a configuration file (JSON) on the local file system using JavaScript where I can write and modify data without losing it when the application is restarted? Any suggestions or solutions for this problem? Thank you for your assista ...

Ways to bypass browser pop-up blockers when using the window.open function

I am displaying an HTML retrieved from the backend. printHtml(htmlContent) { var windowToPrint = window.open('', '_blank'); windowToPrint.document.write(htmlContent); setTimeout(function () { windowToPrint.document ...

Angular2: Utilizing filter and search functionalities for an unordered list

Is there a way to implement filtering for an unordered list in Angular using an input field? This specific component creates an unordered list upon page load by fetching data from a JSON file and using the *ngFor directive along with a service. Below is t ...

Modifying the nginx configuration file for an Angular application: a step-by-step guide

After deploying my Angular application on an nginx server, I encountered a problem. When I accessed http://**.8.100.248:30749, it displayed the default index.html page from the nginx server instead of my actual application located in the html folder under ...

Tips for extracting IDs from multiple checkboxes that have been selected upon submission in an Ionic 2+/Angular 2+ environment

I am facing an issue with retrieving the ID of the checked item upon submission. While I can successfully fetch the selected ID on change, I am unable to do so on submit. It is worth noting that the data I am receiving does not include a "checked" value. T ...

When utilizing *ngIf in Angular 2, the issue of #elmentRef remaining undefined still persists

When using #elementReference with *ngIf in Angular 2, the element reference remains undefined even after the *ngIf expression evaluates to true. In this example, the value of the input will not be displayed. <input *ngIf="true" type="text" #myRef (inpu ...