A
A
Alex102142021-05-05 10:56:27
Angular
Alex10214, 2021-05-05 10:56:27

What is the error when creating a variable of type FormGroup?

Hello everyone, I have this code:

import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';

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

   loginForm: FormGroup;
 

  constructor(
  ) { }

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

  onLogin(): void {
   
    }
    
  }


In it, the variable "loginForm" is highlighted in red and the following error occurs:
"Property 'loginForm' has no initializer and is not definitely assigned in the constructor."
Tell me what am I doing wrong?? And what is this error?

"loginForm: FormGroup | undefined;" - solves the problem, but if I create new variables, the same error occurs. I don't understand what it's about

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Akulinin, 2021-05-05
@Alex10214

Need to move form initialization code to constructor()

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

Typescript makes sure that all properties are initialized in the constructor. To disable this check, set strictPropertyInitialization=false in tsconfig.json

N
NarkoMan01, 2021-05-05
@NarkoMan01

Try like this

loginForm: FormGroup;
 constructor(
  ) { 
this.loginForm = 'some value'; // Некторое значение
}
ngOnInit(): void {
   
    this.loginForm = new FormGroup({
      email: new FormControl('', [Validators.required , Validators.email]),
      password: new FormControl('', [Validators.required , Validators.minLength(4)]),
    });
  }

A
Alexander, 2021-05-14
@bree7e

Alternatively, you can specify that loginForm can be undefined

export class LoginPageComponent implements OnInit {

   loginForm: FormGroup | undefined; // краткая запись loginForm?: FormGroup;
 
  ngOnInit(): void {
   
    this.loginForm = new FormGroup({
      email: new FormControl('', [Validators.required , Validators.email]),
      password: new FormControl('', [Validators.required , Validators.minLength(4)]),
    });
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question