【问题标题】:Accessing "form" property of a form ElementRef shows TypeScript error访问表单 ElementRef 的“表单”属性显示 TypeScript 错误
【发布时间】:2019-03-22 05:29:11
【问题描述】:

我的模板中有这个表格:

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

我将它作为 ViewChild 添加到控制器中:

@ViewChild('heroForm') heroForm: ElementRef;

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

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

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    只需导入 ngForm 指令

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

    更改您的表单声明

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

    更改表单验证条件

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

    【讨论】:

    • 我听从了您的建议,但this.heroForm.valid 给了我一个错误,因为 this.heroForm 在ngOnInit() 上未定义。我暂时解决了将您的逻辑添加到ngAfterViewInit() 的问题。还有其他建议吗?
    • ngAfterViewInit() 很好。
    【解决方案2】:

    ElementRef 不包含任何名为form 的属性。但是,您创建的#heroFormNgForm 类型,它包含form 属性。

    由于 ts 编译,您会收到错误消息。它在ElementRef 中找不到名为form 的属性,并给您错误。在运行时,由于它的 javascript,您不会收到错误并且代码可以正常工作。

    要消除错误,您可以将属性读取为NgForm,如@Boobalan 的答案中给出的那样,或者您可以简单地将heroform 的类型转换为any 而不是ElementRef

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

    【讨论】:

    • @ViewChild('configForm') configForm: NgForm; 怎么样?合适吗?
    【解决方案3】:

    虽然 Boobalan 的回答是正确的,但要坚持使用类型检查,您可以避免使用 any 并简单地使用类型 NgForm,例如:

    @ViewChild('heroForm') heroForm: NgForm;
    
    if (heroForm.valid){
     ...
    }
    

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-03
        • 1970-01-01
        • 2018-03-24
        • 1970-01-01
        • 2015-05-18
        • 2017-06-27
        • 1970-01-01
        • 2022-01-16
        相关资源
        最近更新 更多