首页 > 解决方案 > 如何使用反应形式设置不同的输入类型?

问题描述

我正在构建一个带有嵌套输入的表单。我找到了一个我需要的例子,我正在尝试在我的应用程序中实现它。我没有得到的是如何根据表单的元数据有条件地显示输入类型。

这是标记:

<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'>

标签: formsangular8

解决方案


我通过以下步骤成功实现了您想要的结果,您可以根据自己的情况进行调整:

首先创建一种字段生成器组件。它进入输入 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) 方法的结果。

所以基本上你有这四个步骤:

  1. 根据需要创建带有字段的 JSON 配置
  2. 创建您需要的表单控件或表单组
  3. 将每个字段及其配置和表单控件传递给字段生成器
  4. 让字段生成器使用您想要的类型和您需要传递的所有信息(例如验证、选择选项等)创建每个字段

我发现这种方法非常简单,在复杂的项目中,它非常适合数十种类型的输入(例如,我可以显示日期选择器、滑块、输入文本等,只需添加一个类型并扩展配置 JSON )

我相信你会发现这个答案很有帮助,或者至少,我希望如此!


推荐阅读