【问题标题】:setValue is not a property of EelementRefsetValue 不是 EelementRef 的属性
【发布时间】:2018-05-17 10:19:23
【问题描述】:

我正在测试这个 HTML 表单:

<form  name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm">
<input #inputValid type="text" class="form-control" name="nombre" id="field_nombre"
       [(ngModel)]="paciente.nombre" required/>

我测试输入的有效性,这意味着如果它是空的,它应该会失败。 我在组件中使用 ViewChild 引用了 input 元素,如下所示: >

export class PacienteDialogComponent implements OnInit {

 @ViewChild('inputValid') inputValid: ElementRef;
 ......

我这样测试它:

fit ('If blank it should be invalid', async(() => {                  
   comp.inputValid.setValue('');
  //comp.inputValid.controls['paciente.nombre'].setValue(''); 
  //OUTPUTS CANNOT READ paciente.nombre of undefined
  expect(inputElement.valid).toBeFalsy();
}));

我在这里遇到的错误是:

SetValue 不是函数。

如果我使用控件,错误就像在该行的注释中一样:

无法读取未定义的属性。

如何测试此输入的有效性?表单是模板驱动的角度。

【问题讨论】:

  • 你为什么不检查paciente.nombre?不需要 viewChild
  • 怎么样?获取 HTMLElement 引用的唯一方法是使用 ViewChld

标签: javascript html angular setvalue


【解决方案1】:

首先,如果您在输入控件中有“必需”,我不明白为什么需要手动检查。
无论如何,您不应该通过 ViewChild 组件进行检查,您可以直接检查绑定到表单的类的字段(又名 paciente.nombre)。
但是,如果您有理由访问 html 元素,则必须使用

comp.inputValid.nativeElement.value = .....

希望对你有帮助!

【讨论】:

  • 如何直接测试 paciente.nombre 的例子?如果它的值是否为空
  • 或者更好地测试它是否是文本
  • 如果你有
  • 什么意思???用户也可以输入数字!!!这是错误的。我应该测试它是否只有字母或数字
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
相关资源
最近更新 更多