简体   繁体   中英

How do you access a single property in an array of objects in Angular 6 typescript?

I am currently making a budget app. I have an array of expenses that I can add to with a price property. It is constructed off a expense.model.ts. I am trying to access the price property within Typescript. I can already access it on HTML with the ngFor loop. Is there a way to do it within TypeScript with a for loop?

expenses.service.ts

import { Injectable } from '@angular/core';
import { Expense } from '../expenses-list/expense/expense.model';
@Injectable({
  providedIn: 'root'
})
export class ExpensesService {
  expenses: Expense [] = [
    new Expense('car payment', 350) // price
];
constructor() { }
onAddExpenseToExpenses(expense: Expense) {
  this.expenses.push(expense);
}

// EXAMPLE //
onCalculate() {
  // get prices from listed items
  // add all the prices
  // subtract income from sum of prices
}

Sorry if I am not that clear. I just started using Angular 6.

Thanks for your help! =)

Here is my expense model

export class Expense {
  private item: string;
  private price: number;

constructor(item: string, price: number) {
    this.item = item;
    this.price = price;
  }
}

TypeScript and JavaScript are almost the same without Type and Interface. You should learn and reference JS docs

There are many ways to do with loop:

For:

  let sumPrices = 0;
  for (let i = 0; i < this.expenses; i++) {
    sumPrices += this.expenses[i].price;
  }

For ... of:

  let sumPrices = 0;
  for (const o of this.expenses) {
    sumPrices += o.price;
  }

Array map:

  // get prices from listed items
  // add all the prices
  const sumPrices = this.expenses.reduce((acc, o) => acc + o.price, 0);

You can simply use for loop in typescript

define expenses like this

expenses: Array<Expense>

and in constructor please write code below

this.expenses = new Array<Expense>()
let x = new Expense('car payment', 350);
this.expenses.add(x);
//or
this.expenses.push(x);

after that in onCalculate write this

let sum = 0
for (let item of expenses) {
   sum += item.Price;
}

for more information about Loop study Iterators and Generators on typescriptlang website

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM