我正在测试这个 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/