1

I'm using ViewChild for angular form submit. This is my code,

app.component.ts

import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    @ViewChild('f') signupForm: NgForm; 

    onSubmit(){
        console.log(this.signupForm);
    }
}

app.component.html

<form #f="ngForm" (ngSubmit)="onSubmit()" novalidate></form>

But I'm getting this error,

src/app/app.component.ts:11:21 - error TS2564: Property 'signupForm' has no initializer and is not definitely assigned in the constructor.

11 @ViewChild('f') signupForm: NgForm;

vimuth
  • 5,064
  • 33
  • 79
  • 116
  • Does this answer your question? [Property '...' has no initializer and is not definitely assigned in the constructor](https://stackoverflow.com/questions/49699067/property-has-no-initializer-and-is-not-definitely-assigned-in-the-construc) – Beller Mar 26 '21 at 09:21
  • I tried adding constructor like that but didn't work :( – vimuth Mar 26 '21 at 09:23
  • What version of TypeScript are you using? [Strict Class Initialization](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html) – Beller Mar 26 '21 at 09:31
  • It's looks like work in a simple stackblitz:https://stackblitz.com/edit/angular-ivy-7b3a3e?file=src%2Fapp%2Fapp.module.ts (check if you're import FormsModule in your module or try use `@ViewChild('f') signupForm: NgForm=null;` – Eliseo Mar 26 '21 at 09:37
  • I have added **FormsModule** inside `app.module.ts` and tried `@ViewChild('f') signupForm: NgForm=null;` too now but unfortunately didn't work :'( – vimuth Mar 26 '21 at 09:44
  • Think I have `"typescript": "~4.1.5"` – vimuth Mar 26 '21 at 09:46

2 Answers2

6

Finally found an answer. I had to make strictPropertyInitialization flag to false inside tsconfig.json. Adding this since someone came up with same issue would find this useful. (You may have to use ng serve again)

tsconfig.json

{
  "compilerOptions": {
    ...
    "strictPropertyInitialization": false
  }
}
vimuth
  • 5,064
  • 33
  • 79
  • 116
6

You could also do this:

@ViewChild('f') signupForm!: NgForm; 

With the ! operator you basically say: I know what I'm doing and I know that angular will set this value for me. See this answer for more information about the operator.

Mihai238
  • 1,087
  • 13
  • 26
  • 1
    This fixes the error message but doesn't work by refocusing the input. @vimuth answer doesn't fix the error highlighting message but works like charm by focusing the input correctly. Tested in Angular 12+ – webblover May 16 '22 at 06:21