首页 > 解决方案 > Angular CLI 8 - json 模式的正式自定义选择(草案 4)

问题描述

我在让我的 json 模式(草案 4)完全使用 Angular-Formly 表单自定义模板时遇到了一些困难。我已经为各种数据类型制作了几个模板,并且在 Angular CLI 中使用 select 标记为下拉菜单设置了模板。我发现了很多关于如何为较新的 json 模式制作选择组件的示例,但不适用于使用枚举(请参阅:我的 json 部分)进行选择的旧模式。

这是我的 json 部分:

"hardware": {
    "type": "object",
    "title": "hw.net",
    "properties": {
        "network-0": {
            "type": "string",
            "title": "hw.net.types",
            "enum": [
                "dhcp",
                "static"
            ],
            "default": "dhcp"
        }
    }
}

这是我在 Angular 中的方法(更新:26.03.2020,14:37):

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

@Component({
  selector: 'formly-enum-type',
  template: `
    <mat-label *ngIf="to.label">{{ to.label | translate }}</mat-label>
    <mat-select [formControl]="formControl" [formlyAttributes]="field" (selectionChange)="to.change && to.change(field, formControl)">
      <ng-container *ngFor="let item of to.options">
        <mat-option [value]="item">{{ item }}</mat-option>
      </ng-container>
    </mat-select>
  `,
})

export class EnumTypeComponent extends FieldType { }

意外结果:

意想不到的结果

我的脚本显然有些不完整甚至是错误的。我试图弄清楚,如何正确地将“枚举”部分加载到我的“选项”标签中。当前结果是带有对象而不是文本的下拉菜单。请记住,这个 json 模式是使用http://json-schema.org/draft-4/schema#创建的,它必须保持这种方式。

任何帮助表示赞赏!

谢谢你。

更新(已解决)

能够使用 json 管道功能来解决这个问题,以查看对象中的内容。之后,我能够修复我的脚本,以便正确显示对象项目。

如果有人需要做类似的事情,这是我的固定组件。

@Component({
  selector: 'formly-enum-type',
  template: `
    <mat-label *ngIf="to.label">{{ to.label | translate }}</mat-label>
    <mat-select [formControl]="formControl" [formlyAttributes]="field" (selectionChange)="to.change && to.change(field, formControl)">
      <ng-container *ngFor="let item of to.options">
        <mat-option [value]="item.value">{{ item.label }}</mat-option>
      </ng-container>
    </mat-select>
  `,
})

export class EnumTypeComponent extends FieldType { }

标签: angular-materialjsonschemaangular-formlyangular-cli-v8

解决方案


能够使用 json 管道功能解决这个问题{{ item | json }},看看我的对象里面有什么。之后,我能够修复我的脚本,以便正确显示对象项目。我在上面的更新中包含了我的固定组件脚本。


推荐阅读