从 formArray 控件打字稿触发选择更改事件

问题描述 投票:0回答:1
angular typescript angular-reactive-forms formarray formgroups
1个回答
0
投票

解决此问题的方法是在设置 dataAttributeId 控件的值后手动调用 refreshUserDataAttributeValuesByAttrId 方法。您可以在 bindValuesToDynamicForm 方法中执行此操作,在该方法中迭代数组并设置值。

具体操作方法如下:

bindValuesToDynamicForm() {
  const array: any = [
    { dataAttributeId: 1, dataAttributeValues: "4,5" },
    { dataAttributeId: 2, dataAttributeValues: "2,3" }
  ];

  const userDataAttributesFormArray = <FormArray>this.userForm.get('userDataAttributes');

  array.forEach((x, i) => {
    userDataAttributesFormArray.push(this.addUserDataAttributes(x.dataAttributeId, x.dataAttributeValues.split(',')));

    // Manually call the method to refresh the List2 array at the current index
    this.refreshUserDataAttributeValuesByAttrId(x.dataAttributeId, i);
  });
}

将新组推送到表单数组后,将使用当前的 dataAttributeIdindex 调用 refreshUserDataAttributeValuesByAttrId 方法,这应该会按预期更新您的 List2 数组。

但是,为 dataAttributeValues 控件设置值是不够的,因为数组中的值是字符串,而 mat-option 中的值可能是不同的对象。您需要从 List2[i] 找到正确的对象以设置为 dataAttributeValues 控件的值。

要设置正确的值,您可能需要修改 addUserDataAttributes 方法,从 List2[i] 中查找正确的对象,以设置为 dataAttributeValues 控件的默认值。您可以在使用 refreshUserDataAttributeValuesByAttrId 方法填充 List2[i] 数组后执行此操作。

以下是如何执行此操作的粗略想法:

addUserDataAttributes(dataAttributeId: number, dataAttributeValues: any, index: number): FormGroup {
  // Find the correct objects from List2 to set as the default values
  const correctDataAttributeValues = this.List2[index]?.filter(attr => dataAttributeValues.includes(attr.dataAttributeValueId)) || [];
  
  return this.formBuilder.group({
    dataAttributeId: [dataAttributeId],
    dataAttributeValues: [correctDataAttributeValues]
  });
}

在您的 bindValuesToDynamicForm 方法中,更新对 addUserDataAttributes 的调用以传递索引:

userDataAttributesFormArray.push(this.addUserDataAttributes(x.dataAttributeId, x.dataAttributeValues.split(','), i));
© www.soinside.com 2019 - 2024. All rights reserved.