我正在使用ngFor获取标签并在angular 7中的特定div标签中选择下拉列表。但是,如果我从任何一个select下拉列表中选择选项,它的更改就会发生在div标签的所有select下拉列表中
<div class="row">
<ng-container *ngFor='let item of Bedroom.PBeda'>
<div class="col-lg-3 col-md-6 col-sm-6 col-12">
<span class="font-wt-600">{{item.PBedName}}</span><br /><br />
</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-12">
<select class="form-control" name="value" id="bedID{{item.PBedID}}"[(ngModel)]="beds.value (ngModelChange)="onChangeBedsDetails($event,item.PBedID)">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</ng-container>
</div>
答案 0 :(得分:1)
所有下拉列表值都发生变化的原因是,对于所有下拉列表,您拥有相同的ngModel
,而是将这些值存储在数组中,如下所示:
组件HTML:
<div class="row">
<ng-container *ngFor='let item of Bedroom.PBeda'>
<div class="col-lg-3 col-md-6 col-sm-6 col-12">
<span class="font-wt-600">{{item.PBedName}}</span><br /><br />
</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-12">
<select class="form-control" name="value" id="bedID{{item.PBedID}}"
[(ngModel)]="beds.value[item.PBedID]" (ngModelChange)="onChangeBedsDetails($event,item.PBedID)">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</ng-container>
</div>
组件TS:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
beds: any = {
value: []
}
Bedroom: any = {
PBeda: [
{
PBedID: 1,
PBedName: 'hello'
},
{
PBedID: 2,
PBedName: 'hello2'
}
]
}
onChangeBedsDetails(event, id) {
console.log(this.beds.value[id]);
}
}