2

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

VIK6Galado
  • 650
  • 14
  • 32
  • Do you want to referrence the object property ? then you'll need to use getters: https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers – Mehdi Benmoha Nov 02 '19 at 18:40

2 Answers2

2

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>
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
0

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) }
    ];
brandt.codes
  • 923
  • 2
  • 9
  • 19