问题描述
我正在尝试在 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'],}]
})]
解决方法
就我而言,我必须将选项: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>