我使用的是angular6 multi-select,它有一个来自ngOnInit上的角服务的对象数组中的项列表,它正在传递到multi-select中:
this.sensorTypes = [
{ label : "Power", value : "P"},
{ label : "Current", value : "C"},
{ label : "Voltage", value : "V"}
]在默认情况下,我希望在表单加载时在multi-select中设置2个值。为此,我将ngModel绑定到multi-select上,并在该变量中设置ngOnInit的值,如下所示
this.selectedAttributes = [
{label : "Current", value : "C"},
{label : "Voltage", value : "V"}
]在我的component.html中,我创建了这样的multi-select:
<div class="form-group row">
<div class="col-sm-10">
<ng-select
[ngClass]="'ng-select'"
[(ngModel)]="selectedAttributes"
[ngModelOptions]="{standalone: true}"
[options]="sensorTypes"
[multiple]="true">
</ng-select>
</div>
</div>但是,在多选择中,默认情况下值并不是设置的。
发布于 2019-02-21 06:56:26
您应该使用[items]输入绑定而不是[options]
<ng-select
[items]="sensorTypes"
bindLabel="label"
[multiple]="true"
placeholder="Select"
[(ngModel)]="selectedAttributes">
</ng-select>在组件的module.ts上,导入NgSelectModule。如果您还没有导入您的FormsModule,您应该这样做,因为它需要导入才能与ngModel进行双向绑定才能工作。
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
.
.
@NgModule({
imports: [
FormsModule,
NgSelectModule,
.
.
.发布于 2019-02-21 07:18:12
值在多选择中默认不设置。
为此,请将this.sensorTypes[0]分配给ngModel of your ng-select in ngOnInit()
ngOnInit() {
this.selectedAttributes = this.sensorTypes[0]
}这将获得第一个属性作为默认属性。
发布于 2020-02-25 12:13:40
如果同时使用bindlabel和bindvalue,那么首先查找所选值t的索引。
var index= this.sensorTypes.findIndex(x => x.ID ==something);
//this will set value
this.selectedAttributes= this.sensorTypes[index].ID;https://stackoverflow.com/questions/54800920
复制相似问题