首页 > 解决方案 > 如何在 *ngFor 列表中分配独立于 [(ngModel)] 并选择 HTML 标记

问题描述

我对 [(ngModel)] 有疑问,它将我的所有选择同步到变量

我的变量是 selectStations = [];

所以,当我在里面选择一个选项时,它将呈现所有选择以选择相同的选项并分配给变量中的所有插槽(见下图,看看它覆盖了所有可用的插槽)

打字稿:

      stations: StationModel[] = [];
      selectStations = [];   
    
      addSlotSelectStation(){
        this.view.loading = true;
        this.selectStations.push(null);
        console.log(this.selectStations);
        this.view.loading = false;
      }
      addSelectStation(index: number, stationId: string) {
        console.log(index);
        this.selectStations[index] = stationId;
      }
      deleteSelectStation(index: number): void{
        this.selectStations.splice(index, 1);
        console.log('delete index', index);
      }

HTML:

     <button class="btn btn-primary" (click)="addSlotSelectStation()">
         add slot
     </button>

<!-- List Group All -->
        <ul class="list-group overflow-auto">
          <!-- Loop List All Select Station -->
          <li
            *ngFor="let selectStation of selectStations; let index = index"
            class="list-group-item"
          >
            <div class="form-inline">
              <!-- Order Number -->
              <span class="mr-3">{{ index + 1 }}</span>
              <!-- Selection Dropdown -->
              <select
                #selectnow
                class="form-control bg-light col mr-3"
                name="selectStation[{{index}}]"
                formControlName="selectStation"
                size=1
                [(ngModel)]="selectStations[index]"
                (change)="addSelectStation(index, selectnow.value)"
              >
                <option selected value="">choose station...</option>
                <option
                  *ngFor="let station of stations"
                  [value]="station.id"
                >
                  {{ station.name }}
                </option>
              </select>

              <!-- For test debug reasons -->
              <div>{{ selectStations[index] }}</div>
              <div>{{ index }}</div>

              <!-- Delete Select Station -->
              <button
                class="btn btn-outline-info"
                (click)="deleteSelectStation(index)"
              >
                X
              </button>
            </div>
          </li>
        </ul>

结果: 在此处输入图像描述

所以这就是问题所在,我希望它只选择一个,并且每个选择器只分配一个值,而不是覆盖另一个选择器值。

标签: htmlangularformsdrop-down-menungmodel

解决方案


[已解决] 我将其从 [(ngModel)] 更改为使用 FormArray。当它在输入/下拉列表等中进行迭代时,这非常有用。

这个链接超级有用,看看吧!:) Angular Reactive Forms:FormArray 终极指南


推荐阅读