angular - 如何在angular6中的ng-select中设置默认值?
问题描述
我正在使用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>
但是默认情况下,在多选中未设置值。
解决方案
您应该使用[items]
输入绑定而不是[options]
<ng-select
[items]="sensorTypes"
bindLabel="label"
[multiple]="true"
placeholder="Select"
[(ngModel)]="selectedAttributes">
</ng-select>
在组件的 module.ts 上,导入NgSelectModule
. 如果你还没有导入你的FormsModule
,你应该这样做,因为它需要被导入以进行 2 路绑定ngModel
才能工作。
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
.
.
@NgModule({
imports: [
FormsModule,
NgSelectModule,
.
.
.
推荐阅读
- python - 用 Python re 替换为自定义函数
- android - 在 Kotlin 的 Android Studio 中更改应用程序标题颜色
- r - 通过 r 和 ggplot2 中的 for 循环绘制许多函数
- c++ - 我们如何考虑这个问题中变量的约束?
- azure-api-management - APIM 操作安全
- c# - 对同一列表中的元素进行分组和合并
- android - Flutter中的Android重复依赖问题
- python - 提高 scipy 的 Anderson-Darling 2 样本测试的性能
- laravel - Laravel 数组上的多对多查询过滤器
- c++ - 布尔变量的原子增量(CUDA)