首页 > 解决方案 > 在 Angular 11 中使用 ng-select 和 ngx-formly

问题描述

我正在尝试在 Angular 11 中使用 ng-select 和 ngx-formly。我一直在关注官方文档提供的教程。 https://egghead.io/lessons/angular-use-3rd-party-form-controls-with-angular-formly

我当前的实现给了我以下错误: 在此处输入图像描述

如果我能得到帮助来确定我的代码是否出错或者我是否错过了任何步骤,那就太好了。

以下是我的实现:

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { FieldType } from '@ngx-formly/core';

@Component({
    selector: 'formly-ng-select',
    template: `<div class="mat-input-infix mat-form-field-infix">
    <ng-select
       [items]= "(to.options|formlySelectOptions:field|async)!"
       [placeholder]="to.label || 'placeholder'"
       [bindValue]="to.bindValue || 'value'"
       [formControl]="formControl">
    </ng-select>
  </div>`
})
export class NgSelectFormlyComponent extends FieldType {
  formControl!: FormControl;}

我在我的主要组件中使用上述自定义模板,如下所示:

fields: FormlyFieldConfig[] = [
 {
    key: 'nationId',
    type: 'my-autocomplete',
    // type: 'select',
    templateOptions: {
      label: 'Nation',
      options: this.dataService.getNations()
    }
  }]; 

我还在我的 app.module 中添加了它,如下所示:

FormlyModule.forRoot({
 types: [{
   name: 'my-autocomplete',
   component: NgSelectFormlyComponent,
    // wrappers: ['form-field'],
 }]
})]

标签: angulartypescriptangular-formsangular-ngselectngx-formly

解决方案


就我而言,我必须将选项: Observable 引用到组件变量并从模板中调用该变量以使用异步管道加载选项。

在分配了 observable 之后,我还添加了一个加载状态来呈现 HTML

不知何故,编译器无法检测到它的 T[] | Observable 作为正式选项的数据类型;

样本:

export class ComponentName extends FieldType implements OnInit {
    options$: any;
    loaded = false;

    constructor() {
        super();
    }

    ngOnInit() {
        this.options$ = this.to.options;
        this.loaded = true;
    }

}

组件模板:

<ng-select ..>
    <ng-option *ngFor="let option of options$ | async">...</ng- 
    option>
</ng-select>

推荐阅读