VIK6Galado
VIK6Galado

Reputation: 680

How to pass s same object's property to a function in Angular?

I have an interface for employee as shown below

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

component that implements 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;
  }

}

Here, i'm trying to compute the monthly salary by using the interface calculateMonthlySalary method and trying to display in view using *ngFor but getting below error

ERROR ReferenceError: annualSalary is not defined

Please Correct me where i'm doing wrong

Upvotes: 2

Views: 190

Answers (2)

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

Working Demo 1

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

When you are adding objects of Type IEmployee to the array, the object itself doesn't understand annualSalary, so you have to add it in the calculateMonthlySalary() function

To do it dynamically,you can create a Employee Class:

Working Demo 2

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>

Upvotes: 2

brandt.codes
brandt.codes

Reputation: 923

It is because annualSalary is a key and not a value in this object.

Try this:

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

Upvotes: 0

Related Questions