1

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

pjpscriv
  • 866
  • 11
  • 20
user
  • 27
  • 11

2 Answers2

0

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);
  });
});
pjpscriv
  • 866
  • 11
  • 20
HariHaran
  • 3,642
  • 2
  • 16
  • 33
  • Thanks @Hariharan ,so after I subscribed to the API (I will get the response) My requirement is how to populate in select dropdown in angular formly. Can you please edit the ts code then it will be more helpful for me – user May 24 '21 at 04:28
0

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');
}
Akhil RJ
  • 312
  • 1
  • 4
  • 19