【发布时间】:2021-12-14 05:44:45
【问题描述】:
我的 [(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>
这就是问题所在,我希望它只选择一个,每个选择器只分配一个值,而不是覆盖另一个选择器值。
【问题讨论】:
-
试试 [(ngModel)]="selectStations[index].id"。你的选择和你的价值观之间的联系,它必须是相同的。如果您的选项具有 id 值,则您的选择必须与该 id 连接。
-
怎么样?我的变量 selectStations 是一个数组,我在其中只收集一个 stationId,还是需要从 stationId 更改以保留 StationModel 对象?
-
你能在 Stackblitz 上分享你的代码吗?
-
对不起,我没有太多时间,但我会从 ngModel 改为 FormArray。我认为它可能会解决一些问题。感谢您的帮助如果我有任何更新,我会在这里回答我自己的问题
标签: html angular forms drop-down-menu ngmodel