多个 selects select 相同的选项

multiple selects select the same option

在我的项目中,我有一个 table,其中根据以前的 selection 插入了各种干预措施。如果有更多干预,在 select 上,如果我在第一次干预时转到 select 一个值,它也会在第二次干预时发生变化。如何使 select 离子独立?

<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
<option [value]="1" [attr.disabled]="element.priceVis === 0 ? 'disabled' : null">Visible Surface</option>

[] 作为属性将是数据与 ""

内部变量的一种单向绑定

因此,对于您的情况 [value]="1" 意味着您正在将变量 1 分配给 value 属性,而不是将值 1 分配给 value属性。

要做到这一点,您必须写成

value="1"

最后,您的代码应该如下所示

<option value="1" [attr.disabled]="element.priceVis === 0 ? 'disabled' : null">Visible Surface</option>

您必须对所有 option 标签进行类似的更改才能使其生效。

请查看 angular's property binding 的文档了解更多详情。

还有

因为变量 surface_type 对于所有循环都是相同的。所以你要么必须把它改成一个数组,就像 Erik 评论的那样。或者你必须在 intervention 数组中的每个对象上保留一个变量 surface_type。并将每个实例替换为

element.surface_type

您的界面 Intervention 应如下所示

interface Intervention {
   ... your objects ...
   surface_type: number|string

}

您生成的 <select> 元素都将其选择的值存储在 surface_type 变量中。您可以通过将 ngModel 语句更改为以下内容来将 surface_type 更改为数组: [(ngModel)]="surface_type[j]" 我在其中使用 *ngFor 中的 j 索引。

正如 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