Home > Software engineering >  Angular 13 NgForm ViewChild issue
Angular 13 NgForm ViewChild issue

Time:01-18

Currently move to Angular 13 and have some issues with this ViewChild and NgForm

    @ViewChild('txtForm', { read: NgForm }) form: NgForm;
    .......

      <form #txtForm="ngForm" (ngSubmit)="onSubmit(txtForm)">
        <input name="first" ngModel required #first="ngModel">
        <input name="last" ngModel>
        <button type="submit">Submit</button>
      </form>

For this syntax when build I get the following error:

Error: src/app/app.component.ts:11:43 - error TS2564: 
Property 'form' has no initializer and is not definitely assigned in the constructor.
    
    11   @ViewChild('txtForm', { read: NgForm }) form: NgForm;

If I change the type to any it works, but why it has an issue with the NgForm

As far as I know, there are no issues with the earlier versions

CodePudding user response:

Problem

There is no issue with the Angular version here. This error is because of your settings:

"strictPropertyInitialization": true

Here if you do not initialize the property either during the declaration or in consturctor then the compiler will throw an error.

Solution

  1. Just set the value of above mentioned property in your settings file (tsconfig.json). Check here

  2. You can also silent this error using the non-null assertion operator(!) like below statement. Check here

    @ViewChild('txtForm', { read: NgForm }) form!: NgForm;
    

CodePudding user response:

It is because of angular cli strict mode

More information link

You can solve your problem with adding ! before : like this

@ViewChild('txtForm', { read: NgForm }) form!: NgForm;

Now what does this sign do?

That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null or undefined here, so don't complain about the possibility of it being null or undefined." Sometimes the type checker is unable to make that determination itself.

complete explanation link

  •  Tags:  
  • Related