Reputation: 55
I'm working on a budgeting app. I have a component that holds values I would like to pass to an array that is stored in it's own file. I am able to get data from the array but I can't seem to figure out how to push data into the array.
Is there a way to even do this or would I have to create another component and store the array in that component?
input.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { USERS } from '../mock-users';
import { Users } from '../Users';
//import { Users } from '../Users';
@Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
@Input() description: string;
@Input() date: Date;
@Input() amount: number;
@Input() category: string;
constructor() { }
ngOnInit() {
}
addExpense() {
console.log('expense added');
}
}
mock-users.ts
import { Users } from './Users';
export const USERS: Users[] = [
{
id: 1,
name: 'Keenan',
username: 'keenan.kaufman',
password: 'admin',
expenses: [{
//var myDate = new Date('2019-5-2T00:00:00');
date: new Date('2019-5-2T00:00:00'),
description: 'Electric Bill',
amount: 42,
category: 'Utilites'
},
{
date: new Date('2019-5-2T00:00:00'),
description: 'Rent',
amount: 350,
category: 'Rent'
}]
}
];
Upvotes: 2
Views: 892
Reputation: 6293
Define a really basic service that hold the data for you, this way you can inject it into any component you need and freely access the data.
import { Injectable } from '@angular/core';
@Injectable(
{
providedIn: 'root'
}
)
export class DataService{
constructor() { }
public users : Users[] = [
{
id: 1,
name: 'Keenan',
username: 'keenan.kaufman',
password: 'admin',
expenses: [{
//var myDate = new Date('2019-5-2T00:00:00');
date: new Date('2019-5-2T00:00:00'),
description: 'Electric Bill',
amount: 42,
category: 'Utilites'
},
{
date: new Date('2019-5-2T00:00:00'),
description: 'Rent',
amount: 350,
category: 'Rent'
}]
}];
}
}
In one of your components you can then access the data like so.
public usersLocal: Users[];
constructor(private dataService: DataService) {}
public ngOnInit(): void
{
this.usersLocal = this.dataService.users;
console.log(this.usersLocal);
// array held in service by reference can now push and / splice etc
}
You could define functions in the service for adding to and removing from the array, and any other actions you require surrounding the data.
Upvotes: 1