forms - 如何使用反应形式设置不同的输入类型?
问题描述
我正在构建一个带有嵌套输入的表单。我找到了一个我需要的例子,我正在尝试在我的应用程序中实现它。我没有得到的是如何根据表单的元数据有条件地显示输入类型。
这是标记:
<form class="tree" [formGroup]="testForm" (ngSubmit)="onSubmit()">
<ng-template #recursiveList let-controls let-prefix="prefix" >
<ng-container *ngFor="let item of controls; let i = index">
<div class="tree-item" [formGroup]="testForm.get(prefix + i)">
<input type="text" formControlName="type">
</div>
<div class="sub-tree" *ngIf="item.get('element')?.controls?.length">
<ng-container
*ngTemplateOutlet="recursiveList; context:{ $implicit: item.get('element').controls, prefix: prefix + i + '.element.' }"></ng-container>
</div>
</ng-container>
</ng-template>
<ng-container
*ngTemplateOutlet="recursiveList; context:{ $implicit: testForm.get('element').controls, prefix: 'element.' }"></ng-container>
</form>
这是元数据:
export const data: TreeItem = {
'element': [{
'name':'age',
'label':'Age',
'fieldType':'select',
'type': '',
'element': [
{ 'name':'dateOfBirth',
'label':'Date Of Birth',
'fieldType':'date',
'type': '',
'element': []}
]
}],
};
我想知道我该怎么做:
<input type="date" formControlName="item.name" *ngIf="item.inputType === 'date'>
<input type="text" formControlName="item.name" *ngIf="item.inputType === 'input'>
解决方案
我通过以下步骤成功实现了您想要的结果,您可以根据自己的情况进行调整:
首先创建一种字段生成器组件。它进入输入 acontrol
和一个field
配置(包括fieldtype
您使用响应式表单创建的 AND 控件)。
该组件如下所示:
<fields-list *ngFor="let field of fieldsList">
<field-generator [ngSwitch]="field.fieldType">
<input *ngSwitchCase="'inputText'" [control]="field.control" type="text" />
<input *ngSwitchCase="'inputNumber'" [control]="field.control" type="number" />
<div *ngSwitchDefault>Field type not supported</div>
<field-generator/>
</fields-list>
然后用字段+控件编译您的配置映射简单字段以获得这样的结构:
fieldsList = [{
...yourFieldData, // -> all the keys you need
name, // a key or a name that identifies the field to get its control
fieldType, // the type you need to display
control // the angular control (individual or part of form group)
},
...
]
其中 'control' 是新的 FormControl(field.name, ...).get(field.name) 方法的结果。
所以基本上你有这四个步骤:
- 根据需要创建带有字段的 JSON 配置
- 创建您需要的表单控件或表单组
- 将每个字段及其配置和表单控件传递给字段生成器
- 让字段生成器使用您想要的类型和您需要传递的所有信息(例如验证、选择选项等)创建每个字段
我发现这种方法非常简单,在复杂的项目中,它非常适合数十种类型的输入(例如,我可以显示日期选择器、滑块、输入文本等,只需添加一个类型并扩展配置 JSON )
我相信你会发现这个答案很有帮助,或者至少,我希望如此!
推荐阅读
- gnuplot - 如何仅使用线点和使用gnuplot的多个图绘制由ID列指定的点?
- reactjs - 如何使用 react-scripts 安装 NPM 插件
- docker - 我们可以控制 .dockerignore 文件中内容的区分大小写吗?
- c# - 无法将 C# 字符串从用户态传递到内核模式 C 并使用它来查找特定的 LDR_DATA_TABLE_ENTRY
- python - Flask 根据激活的按钮获得相同的页面结果
- mysql - 如果我们有多个重复的日期,如何确定所有详细信息都应该放在第一个项目中?
- python - 迭代时如何从列表中删除元素?
- tensorflow - TFLite 交叉编译 arm64 构建错误?
- sql - SQL Server,在时间戳中交换日期
- html - 图像不会缩小以适应带有响应页面的 DIV