How to pre-populate ngselect in Angular?

I am grabbing some items through a http call and then want to pre-populate the ngselect, but using the abstractcontrol.setvalue() method does not seem to work.

Template Code

<ng-select [items]="cars"
         bindValue="code"
         bindLabel="displayName"
         formControlName="car"
         [clearable]="false"
         [searchable]="false"
         id="car"
         placeholder="Select a car">

Component Code

this.setValueForPrePopulatedPlanningDetail('car', car);

private setDefaultValue(fieldName: string, value: any) {
    if (value && value.length > 0) {
    const field = this.myFormGroup.get(fieldName);
    field.markAsDirty();
    field.setValue(value);
    }
}

Answers:

Answer

You need set your result to the list (countries) and then use setvalue to choose the option

Set result to your list in your component:

this.countries = ['XPTO','XPTO2','XPTO3']

Define the following in your html:

<select>
   <option [value]="country" *ngFor="let country of countries">             {{country}}</option>
</select>
Answer

The right way of using ng-select, would be to assign the values to the items input binding.

For instance,

<ng-select [items]="cities2"
  bindLabel="name"
  bindValue="id"
  [multiple]="true"
  placeholder="Select cities"
  [(ngModel)]="selectedCityIds">
</ng-select>

And on your component.ts, you will populate ng-select options by subscribing to the observable returned by the HTTP request, and assigning it the cities2 property.

cities2: any[] = [];

ngOnInit() {
  this.dataService.getData.subscribe(res => {
    this.cities2 = res;
  });
}

This demo might not directly answer your queries, but it shows how the various input bindings (such as items) work with ng-select.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.