[Fixed] FormGroup initializaton issue

Issue

While trying to run the angular app with login form, defined as shown below, it throws an Error:

src/app/pages/auth/login/login.component.ts:12:3 – error TS2564:
Property ‘loginForm’ has no initializer and is not definitely assigned
in the constructor.

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '../../../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;

  constructor(private authService: AuthService) {}

  ngOnInit() {
    this.loginForm = new FormGroup({
      email: new FormControl('', {
        validators: [Validators.required, Validators.email]
      }),
      password: new FormControl('', { validators: [Validators.required] })
    });
  }

  onSubmit() {
    this.authService.login({
      email: this.loginForm.value.email,
      password: this.loginForm.value.password
    });
    console.log("logging in...");
  }

}

Does anyone know what is the correct way to initialize FormGroup?

Solution

do it in the constructor, as per the error message:

constructor(private authService: AuthService) {
  this.loginForm = new FormGroup({
    email: new FormControl('', {
      validators: [Validators.required, Validators.email]
    }),
    password: new FormControl('', { validators: [Validators.required] })
  });
}

or you can just initialize it in your class definition:

loginForm = new FormGroup({
  email: new FormControl('', {
    validators: [Validators.required, Validators.email]
  }),
  password: new FormControl('', { validators: [Validators.required] })
});

this isn’t specifically related to FormGroup, it’s a TypeScript setting that doesn’t allow non nullable properties to not be defined either in the class definition or in the constructor.

if you don’t like this setting, you can modify your tsconfig.json to include this in the compilerOptions:

"strictPropertyInitialization": false

this will allow you to not initialize properties in the constructor, but also won’t warn you if you ever forget to do it. Only thing you really need to remember is that @Input() bindings aren’t ready in the constructor, so don’t try to use them when building a form. Use them to modify or set the value of the form after it’s been built.

Leave a Reply

(*) Required, Your email will not be published