jquery Angular:如何使用formcontrol单独设置select的值

vd8tlhqk  于 2023-10-17  发布在  jQuery
关注(0)|答案(1)|浏览(90)

我有一份食物分类的清单。然后我有一个食物列表的表,还有一个foodcategory字段,它对这个项目属于哪个类别进行分类福尔斯。食物类别基于Guid进行Map,但以用户可读的格式显示。对于每个示例,都使用一个新的表单示例。如何单独设置值。使用验证代码,所有这些都将具有相同的,因为它使用相同的表单控件名称。
下面是我的代码片段。

<tr *ngFor="let food of foodItems" id="{{food.Guid}}" class="alternate-row">
      <td><label>{{food.foodName}}</label></td>
      <td><label>{{food.foodDescription}}</label></td>
      <td>
        <form class="table_form" [formGroup]="tableForm" (ngSubmit)="onTableFormSubmit(tableForm.value)">
          <select class="form-control" formControlName="foodCategorySelect" (change)="onTableFormSubmit(tableForm.value, food.Guid)">
            <option *ngFor="let foodCategory of foodCategoryList" [value]="foodCategory.Guid" [selected]="foodCategory.Guid == food.category">
              {{ foodCategory.categoryName }}
            </option>
          </select>    
        </form> 
      </td>
    </tr>

以下是我的记录值数据:

foodCategoryList
    0: 
    Guid: "b6b64fba-1879-44fb-8a8d-1b26c2229367"
    categoryName: "Starter"
    [[Prototype]]: Object
    1: 
    Guid: "ba9e3828-ddf0-4db4-bff2-2ec668d973d0"
    categoryName: "Dessert"
    [[Prototype]]: Object

    foodList
    0: 
    foodName: "Chicken Wings"
    Guid: "ec34ce1f-5274-4d32-a17f-4a518fef9a1f"
    foodDescription: "Delicious spicy chicken wings served with sauce"
    category: "b6b64fba-1879-44fb-8a8d-1b26c2229367" --starter
    [[Prototype]]: Object

请帮帮我。似乎无法找到一种方法

brjng4g3

brjng4g31#

考虑到您希望每一行都是一个表单,我建议使用模板表单(为简单起见)

<!-- no <form> element needed -->
<select [(ngModel)]="food.category"  <!-- binding of category -->
(ngModelchange)="onTableFormSubmit(food.category, food.Guid)"> <!-- update call when it changes -->
...

应该已经成功了
如果您仍然想使用reactive forms API,那么您需要为每一行创建一个reactive piece的示例,然后将表单放入模型中

foodItemsTableData = this.foodItems.map(food => ({
  ...food,
  categoryControl: 
}))

这有点难看但绑定将是[formControl]="food.categoryControl"
或使索引依赖

// ts
foodCategoriesControls = this.foodItems.map(food => new FormControl(food.category));
// subscriptions to updates could be in typescript file in this case if you want to
...
// html
<tr *ngFor="let food of foodItems; index as i"
<select [formControl]="foodCategoriesControls[i]" (change)="onTableFormSubmit(foodCategoriesControls[i].value, food.value)"

你也可以像在你的例子中那样把类别控件 Package 在表单中,但是这并没有什么意义。

相关问题