首页 > 解决方案 > Angular 2+ 使用模板驱动的表单动态创建表单输入适用于单元测试中的生产错误

问题描述

我正在尝试创建一个动态表单,该表单由用户先前的选择生成和填充。用户选择的每个配置文件都包含一个配置数组,该数组循环通过以创建后续输入。

配置对象看起来很像这样:

 {
      Description: "A name for your security control, can have a maximum of 64 characters"
      MaxLength: 64
      Name: "Name"
      Pattern: "^(.{1,64})$"
      Type: "text"
 }

这一切在生产过程中都可以正常工作,但是当我尝试运行单元测试时出现错误:

 Error: If ngModel is used within a form tag, either the name attribute must be set or the form
  control must be defined as 'standalone' in ngModelOptions.

我正在动态设置名称,所以我不明白为什么这不起作用。

 <div class="sc-config-form__input" *ngFor="let config of profile.Config">
      <label *ngIf="!config.Conditional || isConditionMet(config)" class="cloud-grey-label fillLabel" for="sc{{config.Name}}-text">{{config.Name}}</label>
      <input *ngIf="(!config.Conditional || isConditionMet(config)) && (!config.Type || config.Type =='text')"
              maxlength="{{config.MaxLength}}"
              name="{{config.Name}}"
              [ngModel]="config.Default"
              type="text"  
              id="sc{{config.Name}}-text"
              placeholder="{{config.Name}}"
              pattern="{{(config.Pattern ? config.Pattern : '')}}"
              title="{{config.Description}}"
              [required]="config.Required"
       />
 />

我还尝试使用“let i = index”并将索引动态添加到 name 属性。这使它可以通过测试,但是我的控件的名称是错误的,并且由于种种原因它在生产中不起作用。

有没有更简单的方法来解决这个问题?

标签: karma-jasmineangular2-forms

解决方案


在您的输入标签内,您需要添加

[ngModelOptions]="{standalone: true}"

这将解决您的问题。


推荐阅读