What is the best way to transfer data from a component to a .ts file that contains an array?

I am currently developing a budgeting application and I have a component that is responsible for holding values that I want to pass to an array stored in a separate file. While I can retrieve data from the array, I am facing difficulty in figuring out how to add data to the array.

Is there a method to accomplish this task or would it be necessary to create another component and store the array within that component?

input.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { USERS } from '../mock-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: [{
                    date: new Date('2019-5-2T00:00:00'),
                    description: 'Electric Bill',
                    amount: 42,
                    category: 'Utilities'
                    },
                    {
                    date: new Date('2019-5-2T00:00:00'),
                    description: 'Rent',
                    amount: 350,
                    category: 'Rent' 
                    }]
    }

];

Answer №1

Create a simple data service to store your information, allowing you to inject it into any component and easily 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 access the stored data as shown below.

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 allows for modifications like push or splice
}

You can also add functions to the service for adding or removing items from the array, as well as other necessary actions related to the data.


Explore Angular's Documentation for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I design an avatar image within a button similar to Facebook's style?

I'm currently working on a project that involves adding an avatar and a dropdown menu for account settings to my navigation bar. I've already created the dropdown, but I'm having trouble styling the avatar within the button. The button is ta ...

The connection between Parent and Child components within the Angular framework

Can changes made in a Child component automatically reflect in the Parent component when passing variables from parent to child? If we send any variable from parent to child and then make changes in the Child component, will these changes be automatica ...

Tips for refining a list to only include items that contain every element from a specified array

Is there a way to search for all elements in an array and display them if they are all present? For instance, consider the following: const data = [ { "languages": ["JavaScript"], "tools": ["React", "Sass"] }, { "languages": ["Python" ...

Choosing between JavaScript and Handlebars.js depends on the specific needs

Can anyone explain the advantages of utilizing Handlebars.js or similar libraries over solely relying on JavaScript? Thus far, I haven't come across any functionality in Handlebars that cannot be achieved with just pure JavaScript. ...

What could be causing my Bootstrap accordion to not expand or collapse within my Angular application?

Struggling with my Accordion Angular component that utilizes Bootstrap - the collapsing and expanding feature isn't functioning properly. I've simply copied the bootstrap code into my accordion.component.html. <div class="accordion accord ...

What is the correct method for redefining properties and functions in Vue.js?

Is there a proper method for overriding methods using mixins in Vue.js? While it's possible to mimic inheritance with mixins, what if you only want to extend certain props without completely replacing the entire prop value? For example, let's sa ...

Changing the language can lead to an ExpressionChangedAfterItHasBeenCheckedError when the translated value is found within a mat-option

Choose a value from the dropdown menu, then toggle the switch button. An error message labeled 'ExpressionChangedAfterItHasBeenCheckedError' will appear in the console. Click here for an example This issue cropped up after upgrading my Angular ...

Vue: Displayed list displaying checked checkboxes

My attempt at displaying the selected checkboxes is as follows: <pre>{{ JSON.stringify(selectedAttributes, null, 2) }}</pre> <ul class="list-unstyled" v-for="category in categories" ...

Reactjs: Tips for precisely cropping an image to a specific aspect ratio using client-side techniques

Looking to crop an image with a minimalist approach to achieve a specific aspect ratio. For instance, if we have an image sized at 3038 x 2014 px, and desire a 1:2 aspect ratio, we would crop it to 3021 x 2014 px. The crop would be made from the center of ...

What is the best way to determine Prisma types across various projects?

My current project has the following structure: dashboard -- prisma-project-1 -- prisma-project-2 -- client-of-prisma-project-1-and-prisma-project-2 This dashboard is designed to merge data from two separate databases and display them in a meaningful w ...

Ways to access the content of the chosen <td> element using Vue?

I have a dynamic table where I retrieve data using $.ajax() from a database. The content in the rows is editable, and I need to save the changes made with vue.js. After updating the content, an $.ajax() function with 4 parameters (name, client_id, url, and ...

Arranging the columns of a matrix

My dilemma involves a matrix (or multidimensional array) filled with non-unique values, similar to this example: var matrix = [ [1, 3, 2, 4, 1], [2, 4, 1, 3, 2], [4, 3, 2, 1, 4] ] I am in need ...

Executing a callback function when a window confirmation is triggered during the onbeforeunload event

Currently, I need to implement a feature where a confirmation window pops up when the user tries to close the page. The code snippet for this functionality is included below: window.onbeforeunload=function(){ if(...) { return "Are you sure you want to ...

Encountering a surprise Illegal Token JS Error

I am encountering a persistent "Unexpected Token ILLEGAL" error while attempting to run the script on the page after it has been registered. StringBuilder str = new StringBuilder(); str.Append("<script type='text/javascript&apos ...

Extracting event handlers using @ContentChildren: A guide

I am dealing with a my-button component that needs to be enclosed within a my-button-row component in the following manner: <my-button-row> <my-button [label]="Some Label" (click)="func1($event)"></my-button> <my-button [label ...

Developing a Multi-Faceted Array Utilizing SQL Data

The requirement of the plugin I am using is to provide it with an array structure in JavaScript that looks like this: var data = [ { "id": 1, "name": "University1", "list": [ {"id": 1, "name": "Dorms", "list": ...

A guide to incorporating dhtmlx scheduler into your Angular 4 project

Currently, I am utilizing dhtmlx scheduler to handle my events. While I was able to import the necessary js files successfully, I have encountered an issue when it comes to saving data in the database. My backend is built using Spring Boot framework. Can ...

The error message "Equals is not defined: Selenium IDE Custom Format" indicates that the function "

I've been working on enhancing the functionality of the selenium IDE through custom functions. I successfully added my custom functions to user-extensions.js and they work as expected within the IDE. However, I encountered issues when trying to export ...

The functionality of alpine.js x-for update is not functioning as intended

I have implemented a basic x-for loop on data from the Alpine Store (need it to be global). My objective is to modify a specific row after the table has been rendered by the x-for. Codepen: https://codepen.io/roniwashere/pen/oNMgGyy <div x-data> ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...