Updating elements within a number array using Angular and Typescript

When fetching data from a simulated server, I receive the Object essensplan. The goal is to allow users to modify each value in the essenProWoche array and send it back to the server.

I attempted:

<div>
  <label>Changes:
    <input [(ngModel)]="essensplan.essenProWoche" placeholder="Name">
  </label>
</div>

However, this approach doesn't work because it doesn't return an array.

Alternatively, I tried:

<label *ngFor="let id of essensplan.essenProWoche; let i = index">
  <input type="number" [(ngModel)]="essensplan.essenProWoche[i]">
</label>

This method allows for real-time changes in the browser but does not save the values permanently.

To save the inputs, I utilize the following functions:

essensplan-detail.component.ts

save(): void {
  this.essensplanService.updateEssensplan(this.essensplan)
    .subscribe(() => this.goBack());
}

essensplan.service.ts

updateEssensplan(essensplan: Essensplan): Observable<any> {
  return this.http.put(this.speisekarteUrl, essensplan, httpOptions).pipe(
    tap(_ => this.log(`updated essensplan id=${essensplan.id}`)),
    catchError(this.handleError<any>('updateEssensplan'))
}

Answer №1

If you receive an array of objects from the server, one way to handle it is by converting the array elements into a string representation. For example:

this.mealPlan = [
    { id: 1, mealsPerWeek: [11, 14, 17, 20, 12] },
    { id: 2, mealsPerWeek: [11, 14, 17, 20, 12] }
];

You can then transform it like this:

this.mealPlan.map(item => {
    item.mealsPerWeek = item.mealsPerWeek.join(',');
});

Afterwards, you can utilize it in your HTML template like so:

<ng-template ngFor let-item [ngForOf]="mealPlan">
    <input type="text" [(ngModel)]="item.mealsPerWeek">
</ngtemplate>
<!-- ensure to separate the values with commas -->

Lastly, when you are ready to save the data:

save(): void {
    this.mealPlan.map(item => {
        item.mealsPerWeek = item.mealsPerWeek.split(',');    // revert back to array form
    });
    this.mealPlanService.updateMealPlan(this.mealPlan)
    .subscribe(() => this.navigateBack());
}

Answer №2

Do you want the save function to be triggered automatically whenever a value changes? If so, consider using a formControl and subscribing to the valueChanges event. This way, your save function will be called every time there is a change in the value.

Answer №3

Are you interested in achieving two-way binding functionality?

Any changes made to the value inside the model will automatically update your JSON as well.

Implement this in your HTML:

<div *ngFor="let items of essensplan">
    <div *ngFor="let opt of items.essenProWoche; index as i; trackBy: trackByFn">       
        <input type="number" [(ngModel)]="items.essenProWoche[i]">
    </div>
</div>

Also add this function in your TypeScript file:

trackByFn(index, item) {
   return index;
}

To see a live demo, visit this Stackblitz link

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

Adding video files and subtitle files to our MongoDB database

// backend/server.ts import express, { Application, Request, Response } from 'express'; import mongoose from 'mongoose'; import cors from 'cors'; import dotenv from 'dotenv'; const multer = require('multer&apos ...

Challenge with Updating React Components When Switching Themes

In my React application, I'm facing a challenge with theme switching. There are two themes available: Theme One and Theme Two. To dynamically load theme components, lazy loading has been implemented based on the selected theme. Each theme has its own ...

Ensure to verify the slot for any included content to see if it is vacant

I'm currently facing a dilemma without a clear solution in sight. I have created some custom components that utilize content projection and multi slot transclusion. For instance, I have a Card (Bootstrap) and I want to customize elements like the he ...

Instructions on how to deactivate or unselect a toggle switch by simply clicking on the icon among several icons

In my angular application, there are several icons with a toggle switch on the right side. The default state of the switch is ON. When an icon is clicked, its color changes from white to red. By clicking on the switch, the colored icon reverts back to whit ...

The UI elements are failing to reflect the changes in the data

In an attempt to establish communication between three components on a webpage using a data service, I have a Create/Edit component for adding events, a "next events" component for accepting/declining events, and a Calendar component for displaying upcomin ...

Error: Attempting to access an undefined property ('call') on Next.js is causing a TypeError

Exploring the realms of Next.js and Typescript for a new project! My goal is to utilize next.js with typescript and tailwind CSS by simply entering this command: npx create-next-app -e with-tailwindcss my-project Smooth sailing until I hit a snag trying t ...

Factory function with type constraints and default parameter causing TS2322 error

I have a base class that requires some parameters to be passed... class BaseClass<ItemType> { // Some irrelevant parameters omitted for simplicity... constructor(__items: Iterable<ItemType>) {} } Now, I want to create a factory func ...

Passing validators for reactive forms from parent to child components is proving to be a challenge

Currently, I have a situation where a parent form component is utilizing a child form component within an Angular reactive forms setup. While I am able to successfully set the values in the child form component, it seems that the validators are no longer f ...

What is the process for moving information between files?

I have two files which are named as, employee-rates-controller.ts: private load() { return this.entityService .load(this.$scope.projectRevisionUid) .then(resp => { localStorage.removeItem('employeerates'); this.$ ...

Angular lazy loading routes do not function as intended

I currently have a project that is divided into different modules. Among these modules, the ones that are lazy loaded include the about and contact modules. The navigation menu containing the router links is located in a feature module alongside the header ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

Encountering a mysterious server error after configuring CORS settings accurately as directed in the Microsoft documentation

Previously, I was encountering a 405 Method Not Allowed error, but now it seems to have transitioned into a 0 Unknown Error after configuring CORS for both the controller and start.cs. My current focus is on the Error_connection_refused. Why is it being re ...

Troubleshooting Next.js 14 JWT Session Error in Conjunction with Next Auth - addressing a type

Recently, I delved into working with Next.js 14 and Next Auth 5 beta. However, every time I attempt to log in, I encounter the following error: [auth][error][JWTSessionError] [auth][cause]: TypeError: Cannot read properties of undefined (reading 'user ...

Compiling TypeScript files into multiple JavaScript files using Visual Studio 2015 Update 1

I am working on a project that involves multiple Typescript files and I am trying to find a way to compile specific groups of these files into separate JS files. For example: Scripts\Group1\file1.ts Scripts\Group1\file2.ts Scripts&bso ...

Displaying an array in a fresh window with the help of jQuery

I'm working on a PHP page that includes a PHPlot image and I'm trying to figure out how to add a button that will display the data values either in a new window or an alert screen. However, the array size exceeds 10k values so displaying it in an ...

Angular 5 - Performing Jasmine Testing: Simulating an Error Response on a Genuine HTTP Request

Before I start, I'd like to mention that I am currently in the process of learning Angular 4 as part of an internship. This is all very new to me. Anyway, I have a requirement where I need to simulate an error during an HTTP request in the controller ...

What is the best way to combine two arrays with matching values?

I am working with two arrays. $array1 contains the cat_id and cat_title. $array2 contains the category id (chck_cat_id) and user id (chck_comp_id). If this array exists, it means that the user has access to that category. My goal is to add the user&apos ...

The 'onSubmit' property is not found in the 'CampaignComponent' type

Currently, I am encountering an issue with my app when trying to send data to the API. The problem arises when using ng serve, as it throws an error TS2339: Property 'onSubmit' does not exist on type 'CampaignComponent'. The error disa ...

What is the process for creating a unique Vee-Validate rule in TypeScript?

I am in the process of developing a unique VeeValidate rule for my VueJS component written in TypeScript. This rule is designed to validate two fields simultaneously, following the guidelines outlined in VeeValidate - Cross Field Validation. Here is a snip ...

Retrieve the array elements from a MySQL column based on the specified condition and store them in a PHP variable

My database has two columns: copy (an array) and bookid. Here is my code: $query = mysqli_query($db, "select copy from book_outward WHERE bookid like 'B1'"); while ($row = mysqli_fetch_array($query)) { $copyid = $row['copy']; } Th ...