如何将相同对象的属性传递给Angular中的函数?

时间:2019-11-02 18:31:42

标签: angular typescript

我为员工提供了一个界面,如下所示

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

实现上述接口的组件

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

}

在这里,我试图通过使用界面calculateMonthlySalary来计算月薪,并尝试使用*ngFor在视图中显示,但出现错误了

ERROR ReferenceError: annualSalary is not defined

请纠正我在哪里做错了

2 个答案:

答案 0 :(得分:2)

尝试这样:

Working Demo 1

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

将类型为IEmployee的对象添加到数组时,对象本身无法理解annualSalary,因此必须在calculateMonthlySalary()函数中添加它

要动态执行此操作,可以创建一个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;
 }
}

并像这样使用它:

employees: Employee[];

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

模板:

<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>

答案 1 :(得分:0)

这是因为annualSalary是键,而不是此对象中的值。

尝试一下:

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