html - 如何在 *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>
所以这就是问题所在,我希望它只选择一个,并且每个选择器只分配一个值,而不是覆盖另一个选择器值。
解决方案
[已解决] 我将其从 [(ngModel)] 更改为使用 FormArray。当它在输入/下拉列表等中进行迭代时,这非常有用。
这个链接超级有用,看看吧!:) Angular Reactive Forms:FormArray 终极指南
推荐阅读
- docker - 拉rabbitmq windows docker镜像时遇到问题
- c# - 如何从 Visual Studio 或通过命令行部署到 azure signalr 服务
- javascript - 图像过渡淡入淡出
- node.js - nodejs和mongo的类图
- powershell - 对 CSV Powershell 中的值进行数学运算
- rubymine - 从“导航到班级”菜单中以新拆分方式打开文件
- python-3.x - 来自 Pandas pivot dable 的堆积面积图(matplotlib)
- javascript - 使用 React,我如何水平滚动到可滚动 div 中的选定项目?
- typescript - 如何在打字稿定义中引用打字?
- php - 在codeigniter中组合查询的日期和时间列