Kuba Piłat
Kuba Piłat

Reputation: 41

Angular error TS2564 Property 'formGroup' has no initializer

  formGroup: FormGroup;
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.formGroup = this.formBuilder.group({
      'username': ['', Validators.required],
      'password': ['', Validators.required],
    });
  }


  getError(el) {
    switch (el) {
      case 'user':
        if (this.formGroup.get('username').hasError('required')) {
          return 'login is required';
        }
        break;
      case 'pass':
        if (this.formGroup.get('password').hasError('required')) {
          return 'password is required';
        }
        break;
      default:
        return '';
    }
  }

login angualr app

error TS2564: Property 'formGroup' has no initializer and is not definitely assigned in the constructor.

how do i fix it?

Upvotes: 1

Views: 3211

Answers (2)

Chellappan வ
Chellappan வ

Reputation: 27303

You can use non-null assertion operator to prevent the type checker from throwing error

 formGroup!: FormGroup;

Or

Move all the formGroup intialization to top level

  formGroup = this.formBuilder.group({
      'username': ['', Validators.required],
      'password': ['', Validators.required],
  });
   
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
  }

Upvotes: 2

Roman A.
Roman A.

Reputation: 742

This is something related to the strict initialization.

  1. Add ! to aware this is not initialized:
formGroup!: FormGroup;
  1. Add |undefined as additional type :
formGroup: FormGroup | undefined

Upvotes: 5

Related Questions