javascript - setValue 不是 EelementRef 的属性

标签 javascript html angular setvalue

我正在测试这个 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 is not a function.

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

cannot read property of undefined.

如何测试此输入的有效性?该 eform 是模板驱动的 Angular 。

最佳答案

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

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

希望对您有所帮助!

关于javascript - setValue 不是 EelementRef 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50389006/

相关文章:

javascript - 使用变量设置数组

javascript - 如何使用 Javascript 解析 JSON 文件

angular - 调用嵌套组件函数 angular2

html - 在 Angular 2 应用程序中选择时向按钮添加一个勾号

javascript - 如何比较两个 val()

javascript - 事件 Shift 键组合

javascript - Polymer 数据绑定(bind)到属性时的奇怪行为

javascript - 弃用同步 XMLHttpRequest

html - 获取json网址链接(Youtube)以使用angularjs显示

Angular 4继承的Formcontrol