Adăugați un element la un array existent în Typescript, Angular
-aceasta este lista mea salvată-
export const FORMULARLIST: formular[] = [
{ id: 1, name: 'Max Mustermann', mobileNumber: 123456, secondMobileNumber: 654321, email: '[email ', secondEmail: '[email ', 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" />
-Datele Html cu caseta de introducere-
<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">
´´´ Nu știu cum să adaug un element fără a schimba celălalt ´´´
Răspuns #1
Experimentezi un exemplu clasic de mutație a obiectelor. Același obiect formular este referit de elementele adăugate ale array-ului. De aceea, atunci când faci modificări în obiectul principal, toate referințele se schimbă, deoarece în JS obiectele sunt de tip referință.
Pentru a evita acest lucru, pur și simplu adăugați un nou obiect formular în array-ul vostru
addNew(){
FORMULARLIST.push({...this.formular});
}
În acest fel creați un obiect nou și îl adăugați în array, iar this.formular se referă la obiectul curent care este editat.
Notă: Codul de mai sus folosește operatorul spread pentru a crea o copie a obiectului
Răspunsul #2
poți folosi o variabilă separată în componentă (exemplu => my_task:string;) și în șablon poți adăuga direct [(ngModel)]=my_task;
după aceea, la clic pe buton poți face
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
}
Acesta este rezultatul final pe care îl dorești?
