在使用 json 模式(草案 7)生成动态表单时,我在尝试从与 Formly Forms 一起使用的自定义数组组件中删除/禁用按钮时遇到问题。我已经尝试了各种方法来解决这个问题,但似乎没有任何效果。
我想要实现的是,使用ngIf*
显示/隐藏按钮或类似的东西在组件模板中禁用它们。有时数组组件应该显示这些按钮,有时不应该。这必须取决于在某个地方定义的特定属性,可以轻松检查它并且可以防止按钮呈现。
我试图disable: true
在 json 模式中设置一个属性,但我不知道如何从数组组件访问这个属性(我已经检查了field
组件内的对象 - 没有影响)。我还尝试创建一个新组件,我在其中物理删除了这些按钮并命名它arrayDisabled
(也相应地更新了架构等),但field.fieldGroup
属性被搞砸了(它抓取了一个根本不代表数组的无效对象)所以表单内没有显示任何内容。
对此没有太多的文档,因此感谢您的帮助。
这是我的自定义组件:
import { Component } from '@angular/core';
import { FieldArrayType } from '@ngx-formly/core';
@Component({
selector: 'formly-array-type',
template: `
<div class="mb-3">
<legend *ngIf="to.label">{{ to.label | translate }}</legend>
<p *ngIf="to.description">{{ to.description | translate }}</p>
<div class="alert alert-danger" role="alert" *ngIf="showError && formControl.errors">
<formly-validation-message [field]="field"></formly-validation-message>
</div>
<div *ngFor="let field of field.fieldGroup;let i = index;" class="row">
<formly-field class="col-10" [field]="field"></formly-field>
<div *ngIf="isDisabled(field)" class="col-2 text-right">
<button mat-flat-button color="warn" (click)="remove(i)">-</button>
</div>
</div>
<div class="d-flex flex-row-reverse">
<button mat-flat-button color="primary" (click)="add()">+</button>
</div>
</div>
`,
styles: [
`button {min-width: 40px;}`,
`div.ng-star-inserted {margin-left: 0px; margin-right: 0px;}`,
`div.text-right {padding-left: 0px; padding-right: 0px;}`
]
})
export class ArrayTypeComponent extends FieldArrayType { }
这是我的 json 架构示例(草案 7):
"arrayOfItems": {
"type": "array",
"title": "My Array",
"items": {
"type": "object",
"properties": {
"itemA": {
"type": "string",
"title": "Item A"
},
"itemB": {
"type": "string",
"title": "Item B"
},
"itemC": {
"type": "integer",
"title": "Item C"
},
},
"additionalProperties": false,
"required": []
}
}
这是一段 json 模式的示例模型(它是一个简单的对象数组):
"arrayOfItems": [{ itemA: "Item A" }, { itemB: "Item B" }, { itemC: 0 }]
最后但并非最不重要的一点是,这是我使用的共享模块中的导入段:
imports: [
FormlyModule.forRoot({
types: [
{
name: 'array',
component: ArrayTypeComponent,
defaultOptions: {
templateOptions: {
type: 'array',
},
},
}, ...
提前致谢。