首页 > 解决方案 > 以编程方式设置值 ng-select

问题描述

8

[items] : {id: number, label: string }[]
[bindValue]: id
[bindLabel]: label
([ngModel)] : number[]

我想绑定默认数据,但没有标签。(图片)如果我将bindValue更改为标签,那么这些方块将显示标签

手动选择工作正常。

标签: angular8angular-ngselect

解决方案


我添加这行代码以添加默认选定项目

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([]);
    }
}

推荐阅读