最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing "form" property of a form ElementRef shows TypeScript error - Stack Overflow

programmeradmin3浏览0评论

I have this form in my template:

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

And I'm adding it as a ViewChild in the controller:

@ViewChild('heroForm') heroForm: ElementRef;

When I access the "form" property of it to see if it is valid, it shows a TypeScript error "Property 'form' does not exist on type 'ElementRef'. ".

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

How can I get rid of this error?

Stackblitz example: ponent.ts

I have this form in my template:

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

And I'm adding it as a ViewChild in the controller:

@ViewChild('heroForm') heroForm: ElementRef;

When I access the "form" property of it to see if it is valid, it shows a TypeScript error "Property 'form' does not exist on type 'ElementRef'. ".

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

How can I get rid of this error?

Stackblitz example: https://stackblitz./edit/template-driven-form-demo-1tbb37?file=app%2Fuser-form%2Fuser-form.ponent.ts

Share asked Mar 22, 2019 at 5:29 GeForce RTX 4090GeForce RTX 4090 3,51812 gold badges36 silver badges65 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 5

Simply import ngForm directive

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

change your form declaration

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

change you form validation condition

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

The ElementRef does not contain any property called form. However, the #heroForm that you have created is of type NgForm and it contains the form property.

You get the error because of the ts pilation. It cannot find a property named form in ElementRef and gives you error. At runtime, since its javascript, you dont get error and the code works fine.

To get rid of the error, you can read the property as NgForm, as given in @Boobalan's answer OR you can simply convert the type of the heroform to any instead of ElementRef.

Use @ViewChild('heroForm') heroForm: any; instead of @ViewChild('heroForm') heroForm: ElementRef;

Though Boobalan's answer is right, just to stick with typed check, you can avoid any and simply use type NgForm like:

@ViewChild('heroForm') heroForm: NgForm;

if (heroForm.valid){
 ...
}

Read nativeElement property in ElementRef and in this invocation having some security vulnerabilities [1]. Try the below method. this.heroForm.nativeElement

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

发布评论

评论列表(0)

  1. 暂无评论