Search code examples
angulartypescriptangular-materialangular-ngselect

How to setValue/PatchValue multiple value in ngselect in reactive form


I am facing trouble on populating ng select value from database. I have ng select which consist of languages. a user can have multiple languages. on binding multiple selected value on ng select its showing empty tags. my code is below. on edit i want to display saved languages tags on ng select but its showing empty tags someone please help. I am using reactive form **Image for reference is attached **

HTML

 <ng-select class="w-100" [multiple]="true"   [hideSelected]="true" placeholder="Please Select Language"
            formControlName="language" [bindValue]="language.id"  [bindLabel]="language.name" 
            >
            <ng-option *ngFor="let language of languages" [value]="language.id">{{language.name}}</ng-option>
          </ng-select>

Typescript

this.form.patchValue({ language: this.editData.teacherProfile.teacherProfile.language })

Data is retrieving in this form "language": [ { "_id": "5fb79cdd34ec021e64c2413e", "name": "English", "id": "5fb79cdd34ec021e64c2413e" }, { "_id": "5fb7996034ec021e64c2412a", "name": "Arabic", "id": "5fb7996034ec021e64c2412a" } ],


Solution

  • Make sure the value you are set to the field, is available in the value option of the fields

    Suppose the value set to the options of the select dropdown is id like 2, 3, 4 then you need to set the same value so that the name will get visible there

    In the above case, as you share the data with structure, you need to get the all id's into the one array-like

    languageID = [2, 3, 4, 5]
    

    and patch it to the field directly

       this.form.patchvalue({ languageid: this.languageID })