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

Data Binding in AngularJS appears to be non-functional

Experimenting with AngularJS, I created a small code snippet that doesn't seem to bind data properly. Here is the HTML and JS code for those who prefer not to visit the provided link: first.html <!doctype html> <html ng-app="firstApp"> & ...

Emulate an AngularJS ng-click action

My website has HTML code with three buttons: <button ng-click='showStats(player.data,0)'>Death Match</button> <button ng-click='showStats(player.data,1)'>Champions Rumble</button> <button ng-click='sho ...

Animate my banner images only after they have fully loaded using Jquery

I recently came across a banner image slideshow in jQuery, but it seems to be animating even before the images are fully loaded. This results in the slideshow displaying image descriptions without the actual images themselves. Can anyone help me modify th ...

Unable to retrieve data function properties within Vue.Js Component methods

Looking for some help with setting up a welcome message using an input field in Vue.js. I am trying to store the username in a data property called username: ''. However, when I attempt to access it within the methods, I receive an error stating ...

How to customize the text color of the notchedOutline span in Material UI

I'm currently working on customizing the textfield in materialUI. This is what I am trying to modify. I am facing challenges in changing the color of the span tag that contains the text, and also in maintaining the border color when the textfield is ...

Setting Start and End Dates in Bootstrap Vue Datepicker to Ensure End Date is After Start Date

My Vue.js form includes two BootstrapVue datepickers for holiday management. Users can define the start date and end date of their holiday, with the condition that the end date must be equal to or greater than the start date. Here is my current implementat ...

Adding CSS styles to an HTML page using JavaScript

Unfortunately, I do not have the ability to access the HTML directly as it is generated dynamically by a program. However, I do have access to the JS page that is linked to it. As an example, I am able to manipulate elements using JavaScript like so: ...

Obtaining localStream for muting microphone during SIP.js call reception

My approach to muting the microphone involves using a mediastream obtained through the sessionDescriptionHandler's userMedia event. session.sessionDescriptionHandler.on('userMedia', onUserMediaObtained.bind(this)) function onUserMediaObta ...

Refining Typescript type with specific error for generics

Seeking assistance to comprehend the situation: TS playground The situation involves a store with an exec method, where narrowing down the type of exec param is crucial for a sub process. However, an error seems to arise due to the store type being generi ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

Dispatching information to a designated Google Analytics tracking code

Within our website, we have a unique dimension that is configured on Google Analytics and utilized when sending the page view event: gtag('config', 'UA-TrackingCode', { 'custom_map': { 'dimension1': &apo ...

Encountered a server issue (500 Internal Server Error) when attempting to send a POST

I have been working on a social media app project using React and MongoDB. However, every time I try to register a user, I encounter a POST error in the console. I have reviewed both my client-side and server-side code, but I am still unable to successfull ...

The data is not being displayed in the table

I am encountering an issue while attempting to populate the table with data received through props by looping over it. Unfortunately, the data is not rendering on the UI :( However, when I manually input data, it does show up. Below is my code: Code for P ...

Error: The object does not have the property createContext necessary to call React.createContext

I'm currently exploring the new React Context API in my app. I've also implemented flow for type checking. However, when I add // @flow to a file that contains the code: const MyContext = React.createContext() An error pops up stating: Cannot ...

What is the best way to incorporate a minimum width and maximum width in CSS that add up to 100% when necessary?

Can anyone help me find CSS rules that can set a fixed width for an element (width: 500px) but also allow it to be responsive with max-width: 100% if the container is narrower than the element? I saw this example and it works perfectly: .elem { width: 60 ...

What steps can I take to condense and tidy up this output into a more compact string?

Recently, I've been experimenting with Google's APIs and attempting to create a terminal command that can inform me of the distance and travel time to a particular location. However, I'm running into an issue with the current output format: ...

Building a filter for a union type in TypeScript: a step-by-step guide

Allow me to present an example to demonstrate my current objective. const v1: { type: "S"; payload: string } = { type: "S", payload: "test" }; const v2: { type: "N"; payload: number } = { type: "N", payload: 123 }; type Actions = typeof v1 | typeof v2; ...

Trying to retrieve JSON data from an API in VueJS and successfully logging the results, but struggling to render the data on the page. (I

Having recently transitioned from React to VueJs, I encountered a problem where fetching data using axios.get returns a successful response in the console.log. However, when trying to iterate through the array with v-for, nothing is rendered. If you have a ...

Attempting to incorporate Font-Awesome Icons into the navigation bar tabs

As a newcomer to React, I've been attempting to incorporate Font Awesome icons into my secondary navigation bar. Despite using switch-case statements to iterate through each element, all the icons ended up looking the same, indicating that only the de ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...