Insert a new item into a current array using Typescript and Angular

-This is my curated list-

export const FORMULARLIST: formular[] = [
  { id: 1, name: 'Jane Doe', mobileNumber: 987654, secondMobileNumber: 456789, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1bcc0d9eceecccfd8cdc2cecae7c8c5cdcd80c8c5c8cfc7c49c5c5">[email protected]</a>', secondEmail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4e9f5ecf9fbf9e4d9f8f3f9e9f3f5ecf1efe9f8f1f4dce6eeef">[email protected]</a>', roomNumber: 'B203', task: "Data Management" },];

-This is the structure of my form-

export interface formular {
    id: number;
    name: string;
    mobileNumber: number;
    secondMobileNumber: number;
    email: string;
    secondEmail: string;
    roomNumber: string;
    task: string;
}

-Here is the function for adding a new element to the array. However, when I input something in the HTML form field, the list updates automatically-

addNew(){
FORMULARLIST.push(this.formular);
}


-The button triggering the function-

<input (click)="addNew()" type="submit" value="Add" class="btn btn-success" />

-The HTML data with the input box-

 <span class="input-group-text" id="basic-addon1">Task:</span>
            <input id="newtask" [(ngModel)]="formular.task" type="text" class="form-control" placeholder="Task" aria-label="Username" aria-describedby="basic-addon1">

´´´ I'm struggling with updating only one element in the array without affecting the others ´´´

Answer №1

You are encountering a classic scenario of object mutation. The formular object is being referenced by the elements added to the array. Consequently, any changes made to the main object will affect all the references because JavaScript treats objects as reference types.

To prevent this, simply insert a new formular object into your array

addNew(){
FORMULARLIST.push({...this.formular});
}

By doing this, you create a fresh object and include it in the array, while this.formular still points to the current object being modified.

Important: The code above utilizes the spread operator to generate a duplicate of the object

Answer №2

To utilize a separate variable within the component (for example: myTask:string;), you can directly incorporate it in the template like this: [(ngModel)]=myTask;

Subsequently, upon clicking a button, you can execute the following:

addNew(){
FORMULARLIST.push({
 id: '';
name: '';
mobileNumber: 0;
secondMobileNumber: 0;
email: '';
secondEmail: '';
roomNumber: '';
task: string;
task:this.myTask
});
this.myTask = ''; // reset the input variable
}

Does this result align with your final objective?

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

Link Array Element to [(value)] within Angular

Hey there! I'm currently working with Angular Material and dealing with an Array of products to generate a table in my template. <tbody> <tr *ngFor="let item of productArray | async; let i = index"> Within this loop, I have another l ...

When dealing with errors arising from API calls, Angular can be prone to throwing error messages

I am currently creating an Angular service class to interact with APIs. However, I am facing an issue when handling Internal server errors in the response and need to send an error message to the user. The services are designed for retrieval but encounteri ...

Error Message in Terminal When Launching React Application Using Webpack

I am encountering several errors in the node terminal while attempting to launch my react-app [at-loader] ./node_modules/@types/webpack/index.d.ts:23:16 TS2665: The module name in augmentation is invalid. Module 'webpack/lib/dependencies/HarmonyE ...

Angular: Exploring Directives - The Impact of Passing "null" versus an Empty String to the @Input Setter

I've observed an interesting behavior with the @Input setter in a Directive. It seems that when an empty string ("") is passed in the template, the setter method is not initially called. However, if the value "null" or "false" is provided, then the se ...

Guide to modifying text color in a disabled Material-UI TextField | Material-UI version 5

How can I change the font color of a disabled MUI TextField to black for better visibility? See below for the code snippet: <TextField fullWidth variant="standard" size="small" id="id" name=&quo ...

What steps are involved in setting up a SAML service provider using @node-saml/node-saml?

I'm currently working on a SAML SP implementation using the @node-saml/node-saml library. Despite creating the necessary source code, I am facing an issue with the SAML authentication not functioning as expected. Can anyone provide guidance on how to ...

Ways to trigger a function in Angular every 10 seconds

What is the method to utilize Observable function for fetching data from server every 10 seconds? Custom App service fetchDevices (): Observable<Device[]> { return this.http.get(this.deviceUrl) .map(this.extractData) .catch(this ...

There appears to be a TypeError in PrimeNG which states that the function "this._activeIndex.includes" is not recognized

I am working on a component that utilizes an accordion feature. My goal is to have multiple tabs enabled with a custom activeIndex. Below is the code snippet I have implemented: <p-accordion [activeIndex]="index" [multiple]="true"> <p-accordion ...

The functionality of "subscribe()" is outdated if utilized with "of(false)"

My editor is flagging the usage of of as deprecated. How can I resolve this issue and get it working with of? public save(): Observable<ISaveResult> | Observable<boolean> { if (this.item) { return this.databaseService.save(this.user ...

What is the best way to specify a function type that takes an argument of type T and returns void?

I am in search of a way to create a type that can accept any (x: T) => void function: let a: MyType; a = (x: number) => {}; // (x: number) => void a = (x: string) => {}; // (x: string) => void a = (x: SomeInterface) => {}; / ...

Update the child component whenever there are changes in the variables of the parent component in Angular 2

I've implemented a MasterComponent that loads the header, footer, sidebar, and more. The header includes a dropdown with options that are set once the user logs in. I need the header to remain constant even when navigating to different routes, each lo ...

What is the best way to fetch a partial JSON response object from an API using JavaScript?

Currently, I am utilizing the One Bus Away API, returning a response object in this format: { "code": 200, "currentTime": 1504150060044, "data": { "entry": { "arrivalsAndDepartures": [ {AnD_item1 ...

I'm encountering an error when trying to use makeStyles

Something seems off with MUI. I was working on my project yesterday and makeStyles was functioning properly, but now it's suddenly stopped working. I'm encountering an error when calling it here: https://i.sstatic.net/tBf1I.png I suspect the iss ...

Error encountered while compiling React application: Module build unsuccessful due to failure in ./node_modules/babel-loader/lib/index.js

Having an issue while trying to compile a React app. After pulling the repo from Github, running yarn install, and then compiling it, I encountered the following error: Module build failed (from ./node_modules/babel-loader/lib/index.js) SyntaxError: {file_ ...

The appearance and functionality of the app undergo a noticeable transformation after being bundled with Webpack

After successfully migrating my Angular 2 project from SystemJS to Webpack using the latest version of Angular2-CLI, I noticed some unexpected changes in the design of the page. Despite minimal adjustments to the project files and Angular2 code during the ...

"Trying to create a new project with 'ng new xxx' command resulted in error code -4048

Whenever I execute 'ng new projectName' in vs code, I encounter the following issue. ng new VirtualScroll ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? SCSS [ http://sass-lang.com ] CREATE Vir ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

When Android build APK is released, HTTP requests fail, yet they work seamlessly during debugging

While debugging, all API calls function correctly. However, when creating a build apk file, the requests are not being called in the build apk. Despite having an SSL certificate on the server, the request still fails to go through. ...

Issues with running Angular 2-4 SETUP on Windows operating system

I recently started working with Angular 2/4 and everything was running smoothly until I followed the instructions on https://github.com/angular/angular-cli. I have Angular 2-4 installed on my machine, but after a recent Windows update, I encountered issues ...

Interference with ElementClickInterceptedException in Selenium is caused by the presence of a WebPack iframe within an Angular application, despite implementing WebDriverWait

Everything was going smoothly with my automation code until suddenly, an ElementClickIntercepted exception started occurring when trying to click the "Sign In" button on the login screen: public class LoginPage { private readonly IWebDriver driver; ...