angular - 在 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'],
}]
})]
解决方案
就我而言,我必须将选项: 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>
推荐阅读
- c++ - 将红色通道与归一化图像相结合
- ios - 为选定的边缘 UIView 添加阴影
- react-native - 仅在 IOS 上的注销导航中反应本机空白屏幕
- javascript - macOS Safari 问题与(getUserMedia)以角度 6 从相机获取视频流 - NotReadableError:I/O 读取操作失败
- javascript - 检查图像扩展 jQuery 以插入 JPG 或 GIF
- c - fprintf 对时间戳计数器有奇怪的影响
- c# - 登录后如何根据角色将用户重定向到不同的主页?
- node.js - 未处理的承诺拒绝警告。Passport.js
- python - 使用 openCV 通过网络摄像头制作实时草图
- javascript - 将日期传递给 componentDidMount 中的函数