Home > Back-end >  Add an element to an existing array in Typescript, Angular
Add an element to an existing array in Typescript, Angular

Time:10-01

-this is my saved list-

export const FORMULARLIST: formular[] = [
  { id: 1, name: 'Max Mustermann', mobileNumber: 123456, secondMobileNumber: 654321, email: '[email protected]', secondEmail: '[email protected]', roomNumber: 'A101', task: "Rechenzentrum" },];

-this is my interface-

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

-And that is the function that should add an element to the array. What it does, but as soon as I put something in my box from my input field in the html file, the list changes too-

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


-the button with 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">Aufgabe:</span>
            <input id="newtask" [(ngModel)]="formular.task" type="text" class="form-control" placeholder="Aufgabe" aria-label="Username" aria-describedby="basic-addon1">

´´´ I don't know how to add one element without changing the other ´´´

CodePudding user response:

you can use a separate variable in the component (example => my_task:string;) and in the template you can directly add [(ngModel)]=my_task;

after that on button click you can do

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

is this the final result that you want ?

CodePudding user response:

You are experiencing a classic example of object mutation. The same formular object is being referenced by the added items of the array. That's why when you make changes in the main object, all the references also gets changed because in JS Objects are a reference type.

To avoid it, simply add a new formular object into your array

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

This way you are creating a new object and adding it in the array and this.formular references to the current object being edited.

Note: The above code uses spread operator to create a copy of object

  • Related