angular8 - 以编程方式设置值 ng-select
问题描述
[items] : {id: number, label: string }[]
[bindValue]: id
[bindLabel]: label
([ngModel)] : number[]
我想绑定默认数据,但没有标签。(图片)如果我将bindValue更改为标签,那么这些方块将显示标签
手动选择工作正常。
解决方案
我添加这行代码以添加默认选定项目
this.heroForm.get('selectedCitiesIds').patchValue([1,2]);
检查这个例子
<form [formGroup]="heroForm">
<div class="form-group">
<label for="state">City</label>
<ng-select *ngIf="isCitiesControlVisible"
[items]="cities"
bindLabel="name"
bindValue="id"
labelForId="state"
[multiple]="true"
placeholder="Select cities"
clearAllText="Clear"
formControlName="selectedCitiesIds">
</ng-select>
<br>
<button (click)="toggleCitiesControl()" class="btn btn-sm btn-secondary">Show/Hide</button>
<button (click)="clearCities()" class="btn btn-sm btn-secondary">Clear</button>
</div>
</form>
和
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'forms-multi-select-example',
templateUrl: './forms-multi-select-example.component.html',
styleUrls: ['./forms-multi-select-example.component.scss']
})
export class FormsMultiSelectExampleComponent implements OnInit {
heroForm: FormGroup;
isCitiesControlVisible = true;
cities: any[] = [
{ id: 1, name: 'Vilnius' },
{ id: 2, name: 'Kaunas' },
{ id: 3, name: 'Pavilnys (Disabled)', disabled: true },
{ id: 4, name: 'Pabradė' },
];
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.heroForm = this.fb.group({
selectedCitiesIds: []
});
this.heroForm.get('selectedCitiesIds').patchValue([1,2]);
}
toggleCitiesControl() {
this.isCitiesControlVisible = !this.isCitiesControlVisible;
}
clearCities() {
this.heroForm.get('selectedCitiesIds').patchValue([]);
}
}
推荐阅读
- pandas - 如何只返回 PANDAS 列中前 5% 的响应
- excel - 我在 excel 中从下面的当前输出中寻找预期的输出
- typescript - 无需嵌套的 TypeScript 类的可理解的 Mixin 链接
- javascript - 使用 JS 命名空间使 Accordion 工作
- javascript - 如何在javascript上定义所选元素的样式
- c - pthread_exit() 和 pthread_join() 不起作用
- codeigniter - 如何使用codeigniter连接到api
- javascript - 如何在 xmlHttpRequest 中发送 csrf 令牌?
- java - 我正在尝试访问docusign API,但在身份验证中遇到错误如何解决?
- node.js - 一个进程运行后,Docker react express ap没有运行