简体   繁体   English

Angular/TypeScript 更新对象数组的元素

[英]Angular/TypeScript update element of array of objects

please forgive if my question is stupid but I have no idea what am I doing wrong.如果我的问题很愚蠢,请原谅,但我不知道我做错了什么。 I have array of objects我有对象数组

export interface IOptionsData {
  option: string;
  optionPrice: number;
  benefit: string;
  benefitPrice: number;
  oneshotPrice: number;
  commitmentPeriod: number;
}

formData: IOptionsData[] = [];

And saving data from form in it并将表单中的数据保存在其中

onOptionChange(i) {
    console.log(i);
    console.log(this.productForm.controls['user_options']);
    this.formData[i].option = this.productForm.controls['user_options'].value[i].option;
    this.formData[i].commitmentPeriod = this.productForm.controls['user_options'].value[i].commitmentPeriod;
    console.log(this.formData);
    ...
  }

On first element everything seems normal在第一个元素上,一切似乎都很正常

My form data:我的表单数据:

表格数据1

And my array data:还有我的数组数据:

数组数据 1

But when I update another item in form, instead of updating that element in array, it updates complete array to that values但是当我更新表单中的另一个项目时,它不会更新数组中的该元素,而是将完整数组更新为该值

表格数据2

数组数据 2

onChange function is called with correct parameter, there is no multiple functions calls onChange function 以正确的参数调用,没有多个函数调用

Have no idea why is this happening不知道为什么会这样

Please if you know any reason why it would请如果你知道为什么它会

Thank you谢谢

EDIT: forgot to mention编辑:忘了提

Before I went with array of objects, I used individual arrays for each value I need to store.在使用对象数组之前,我对需要存储的每个值都使用了单独的 arrays。

  selectedOptions: string[] = [];
  selectedBenefits: string[] = [];
  selectedPrices: number[] = [];
  benefitPrices: number[] = [];
  oneshotBenefitPrices: number[] = [];

And same update worked as intended, only updated value is getting updated并且相同的更新按预期工作,只有更新的值正在更新

this.selectedOptions[i] = this.productForm.controls['user_options'].value[i].option;

EDIT No2:编辑二:

To reproduce this error you don't need html template.要重现此错误,您不需要 html 模板。

Here is part of.ts file这是.ts文件的一部分

export interface IOptionsData {
  option: string;
  optionPrice: number;
  benefit: string;
  benefitPrice: number;
  oneshotPrice: number;
  commitmentPeriod: number;
}

demoOptionsData: IOptionsData = { option: null, optionPrice: 0, benefit: null, benefitPrice: 0, oneshotPrice: 0, commitmentPeriod: 24 };
ngOnInit() {
  /* Initiate the form structure */
    this.formData.push(this.demoOptionsData);
    this.formData.push(this.demoOptionsData);
    this.formData.push(this.demoOptionsData);

    this.formData[1].option = 'TEST';
    console.log(this.formData);
  }

数组数据 3

Solved by comment from @htn formData is an array of the SAME REFERENCE demoOptionsData, so, the result is expected通过@htn formData 的注释解决了一个相同的引用 demoOptionsData 的数组,因此,结果是预期的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM