angular - 在 Typescript、Angular 中向现有数组添加元素

标签 angular typescript

-这是我保存的列表-

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/

相关文章:

javascript - 服务中的 Angular2 函数未定义

javascript - 我的服务仅在我的 ngx 传单 map 上显示最后一个 json 元素标记

javascript - 为什么在 JavaScript 中导入模块有不同的方法?

visual-studio - typescript ES5 配置

javascript - Typescript 应用程序导入和导出的基本问题

google-chrome - typescript :TSX 文件在 Chrome 中显示为空白

css - SCSS : use dynamic variable inside @each

android - 当您的应用程序在后台运行时,Ionic 如何通过摇动打开您的应用程序?

javascript - 如何在javascript中正确存储和显示不同时区的工作时间?

javascript - typescript 类型检查