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

2 Answers 2

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);
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

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
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');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.