首页 > 解决方案 > 多选选择相同的选项

问题描述

在我的项目中,我有一张表格,其中根据之前的选择插入了各种干预措施。在更多干预的情况下,如果我在第一次干预时选择一个值,则在第二次干预时它也会改变。我怎样才能使选择独立?

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<table class="table table-hover table-bordered table-striped" style="display: contents;">
  <caption></caption>
  <thead style="background:#ce5e59; color: white;">
    <tr>
      <th scope="colgroup">Interventions:</th>
      <th scope="colgroup">Surface Type:</th>
      <th scope="colgroup">Price:</th>
    </tr>
  </thead>
  <tbody>
    <ng-container *ngFor="let element of intervention; index as j">
      <tr>
        <td>{{element.int.code}}</td>

        <td>
          <select multiple [(ngModel)]="surface_type">
            <option selected disabled [value]="0">Select</option>
            <option [value]="1" [attr.disabled]="element.priceVis === 0 ? 'disabled' : null">Visible Surface</option>
            <option [value]="2" [attr.disabled]="element.pricePlast === 0 ? 'disabled' : null">Plastered Surface</option>
            <option [value]="3" [attr.disabled]="element.priceBoth === 0 ? 'disabled' : null">Both Surface</option>
          </select>
        </td>

        <td *ngIf="surface_type == 0"></td>
        <td *ngIf="surface_type == 1">{{element.priceVis}}€/{{element.unit}}</td>
        <td *ngIf="surface_type == 2">{{element.pricePlast}€/{{element.unit}}</td>
        <td *ngIf="surface_type == 3">{{element.priceBoth}}€/{{elemento.unit}}</td>
      </tr>
    </ng-container>
  </tbody>
</table>

intervention: Intervention[] = []
surface_type: number: 0

标签: javascripthtmlangulartypescriptngfor

解决方案


正如 Erik 所指出的,您需要让您ngModel成为一个数组:

<select multiple [(ngModel)]="surface_types[j]">

其次 - 您需要将FormsModule包导入 Angular 模块:

import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [
         FormsModule      
    ]

我在 Stackblitz 上创建了 Sandbox,你可以检查一下:

https://stackblitz.com/edit/angular-qsxgaz?file=src%2Fapp%2Fproduct-list%2Fproduct-list.component.html


推荐阅读