-这是我保存的列表-
export const FORMULARLIST: formular[] = [
{ id: 1, name: 'Max Mustermann', mobileNumber: 123456, secondMobileNumber: 654321, email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99d4f8e1d4eceaedfcebf4f8f7f7d9fbfcf0eae9f0fcf5b7fdfc" rel="noreferrer noopener nofollow">[email protected]</a>', secondEmail: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eca18d94a1999f98899e818d8282bf898f838288ac8e89859f9c858980c28889" rel="noreferrer noopener nofollow">[email protected]</a>', 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" />
-带输入框的Html数据-
<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">
´´´ 我不知道如何添加一个元素而不更改另一个元素 ´´´
最佳答案
您正在经历对象突变的经典示例。数组中添加的项正在引用相同的formular
对象。这就是为什么当您在主对象中进行更改时,所有引用也会更改,因为在 JS 中对象是引用类型。
要避免这种情况,只需在数组中添加一个新的 formular
对象即可
addNew(){
FORMULARLIST.push({...this.formular});
}
这样,您就可以创建一个新对象并将其添加到数组中,并添加对当前正在编辑的对象的 this.formular
引用。
注意:以上代码使用spread operator创建对象的副本
关于angular - 在 Typescript、Angular 中向现有数组添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69387773/