访问表单ElementRef的“表单”属性会显示TypeScript错误

时间:2019-03-22 05:29:12

标签: javascript angular typescript

我的模板中有此表单:

<form #heroForm="ngForm" (ngSubmit)="onSubmit()">

我将其添加为控制器中的ViewChild:

@ViewChild('heroForm') heroForm: ElementRef;

当我访问它的“ form”属性以查看它是否有效时,它显示TypeScript错误“ ElementRef”类型上不存在“ Property'form'。 “。

if(this.heroForm.form.valid){
  this.submitted = true;
}

如何摆脱这个错误?

Stackblitz示例:https://stackblitz.com/edit/template-driven-form-demo-1tbb37?file=app%2Fuser-form%2Fuser-form.component.ts

3 个答案:

答案 0 :(得分:1)

只需导入ngForm指令

import {NgForm} from '@angular/forms';

更改表单声明

@ViewChild('heroForm', { read: NgForm }) heroForm: any;

更改您的表单验证条件

if(this.heroForm.valid){
    this.submitted = true;
}

答案 1 :(得分:1)

ElementRef不包含任何称为form的属性。但是,您创建的#heroForm的类型为NgForm,其中包含form属性。

由于ts编译,您将收到错误。它在form中找不到名为ElementRef的属性,并给您错误。在运行时,由于使用了JavaScript,因此不会出错,并且代码运行正常。

要摆脱错误,您可以将属性读为NgForm,如@Boobalan的答案中所述,也可以将heroform的类型转换为any而不是ElementRef

使用@ViewChild('heroForm') heroForm: any; 而不是@ViewChild('heroForm') heroForm: ElementRef;

答案 2 :(得分:0)

读取ElementRef中的nativeElement属性,此调用中存在一些安全漏洞[1]。请尝试以下方法。 this.heroForm.nativeElement

[1] https://angular.io/api/core/ElementRef