[英]How to assign independent of [(ngModel)] in *ngFor list and select HTML tag
I have a problem with [(ngModel)], it syncs all my select to variable我有 [(ngModel)] 的问题,它将我所有的选择同步到变量
my variable is selectStations = [];我的变量是 selectStations = [];
So, when I select an option inside, it will render all select to select the same one and assign to all slot in a variable (see the picture below, just look at it override all slot that is available)因此,当我在里面选择一个选项时,它将渲染所有选择以选择相同的一个并分配给变量中的所有插槽(请参见下图,只需查看它覆盖所有可用插槽)
Typesript:排版:
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: 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>
So That's the problem, I want it just select only one, and assign value only one each selector, not override another selector value.所以这就是问题所在,我希望它只选择一个,并且每个选择器只分配一个值,而不是覆盖另一个选择器的值。
[Solved] I change it from [(ngModel)] to use FormArray. [已解决] 我把它从 [(ngModel)] 改为使用 FormArray。 That's very useful when it come across iterating in the list of input/dropdown and etc.
当它遇到在输入/下拉列表等中进行迭代时,这非常有用。
This Link is super useful, Check it out!这个链接超级有用,快来看看吧! :) Angular Reactive Forms: The Ultimate Guide to FormArray
:) Angular Reactive Forms:FormArray 终极指南
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.