0

我是角度形式的新手。我的要求是将城市(来自后端)放在下拉列表中,但我已经尝试过,但我无法做到这一点。

.service.ts

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

从上面的 API 我必须获取下拉元素并将其放在选择下拉列表中,例如

.ts

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

谁能帮我解决这个问题

4

2 回答 2

0

您可以执行以下操作:

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

然后在方法内部:

private loadOptions(field?: FormlyFieldConfig: Promise<void> {
    if (!field || !field.templateOptions) {
      return;
    }
    field.templateOptions.options = this.http.get(this.baseUrl + '/api/data/xxx/city/getcity');
}
于 2022-01-14T11:17:29.503 回答
0

让我们假设您的 API 返回一个string[]具有要填充到下拉列表中的值。从您的角度组件中,您必须FormlyFields[]构建以准备表单。

我建议您为keyfield送到fields[]. 这将帮助您识别哪个元素是哪个元素并相应地填充数据。

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

在您订阅了API具有下拉列表值的选项后,

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);
  });
});
于 2021-05-24T04:14:31.283 回答