karma-jasmine - 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 属性。这使它可以通过测试,但是我的控件的名称是错误的,并且由于种种原因它在生产中不起作用。
有没有更简单的方法来解决这个问题?
解决方案
在您的输入标签内,您需要添加
[ngModelOptions]="{standalone: true}"
这将解决您的问题。
推荐阅读
- mysql - 如何创建带条件的Mysql动态查询语句
- android - 通过 ADB shell 登录到 Debug UART
- azure - Azure 基本到标准 SKU 负载均衡器升级,无需停机
- mysql - SQL查询总和的多个总和和平均值
- java - 如何让整个项目在 IntelliJ IDEA 中运行?
- python - “func azure functionapp publish”返回错误代码 400
- java - 无法删除片段
- mqtt - mqtt:如何强制执行完整的消息状态,然后是增量
- django - 如何修复 Django 自定义过滤器:“命名空间未绑定错误”
- c# - 阻止用户后结束会话并手动使访问令牌过期