how place the select (dropdown) elements from backend in angular formly

2.2k views Asked by At

I am new to the angular formly .My requirement is to place the cities (coming from the backend )in dropdown but I have tried but I am unable to do this.

.service.ts

getcitiNames(): Observable<any> {
    return this.http.get(this.baseUrl + '/api/data/xxx/city/getcity');
  }

from the above API I have to fetch the dropdown elements and place it in the select dropdown like

.ts

 {
      key: 'Select',
      type: 'select',
      className: 'select-stlyes',
      templateOptions: {
        label: 'Status',
        options: [
          { value: 1, label: 'data1' },
          { value: 2, label: 'data2' },
          { value: 3, label: 'data3' }
        ],
      },
    },

Can anyone help me regarding this

2

There are 2 answers

1
HariHaran On

Let's assume your API is returning a string[] which has the values to be populated in dropdown. From your angular component you must have the FormlyFields[] constructed to prepare the form.

I would suggest you to maintain a unique key for each field object that you push to the fields[]. This will help you in identifying which element is which and populate data accordingly.

 {
      key: 'countries',
      type: 'select',
      className: 'select-stlyes',
      templateOptions: {
        label: 'Status',
        options: [
          { value: 1, label: 'data1' },
          { value: 2, label: 'data2' },
          { value: 3, label: 'data3' }
        ],
      },
 }

After you have subscribed to the API which has the values for dropdown,

yourApi().subscribe((response: any) => {
  const fieldToPopulate = this.fields.find(f => f.key === 'countries');
  // assuming response has values like this: ['Italy','France']
  response.forEach(country => {
    // Ideally `value` will also be dynamic if your API returns a Dictionary<string,string>
    fieldToPopulate.templateOptions.options.push(value:1, country);
  });
});
0
Akhil RJ On

You can do something as follow :

 {
     key: 'Select',
     type: 'select',
     className: 'select-stlyes',
     templateOptions: {
         label: 'Status',
         options: [],
     },
     hooks: {
         onInit: (field) => this.loadOptions(field)
     }
 }

And then inside the method :

private loadOptions(field?: FormlyFieldConfig: Promise<void> {
    if (!field || !field.templateOptions) {
      return;
    }
    field.templateOptions.options = this.http.get(this.baseUrl + '/api/data/xxx/city/getcity');
}