Property 'myForm' has no initializer and is not definitely assigned in the constructor

Viewed 15171
import { Component, HostListener, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'app-contact-form',
    templateUrl: './contact-form.component.html',
    styleUrls: ['./contact-form.component.css'],
})

export class ContactFormComponent implements OnInit {

    myForm: FormGroup;
    constructor(private fb: FormBuilder) {
        this.myForm.valueChanges.subscribe(console.log);
    }

    ngOnInit() {}

    createForm() {
        this.myForm = this.fb.group({
            name: ['', Validators.compose([Validators.required, Validators.minLength(3),
                Validators.maxLength(50)
            ])],
            email: ['', Validators.compose([Validators.required, Validators.email])],
            gender: ['', Validators.required],
            terms: ['', Validators.requiredTrue]
        });
    }

}

Error

Error: src/app/contact-form/contact-form.component.ts:15:5 - error TS2564: Property 'myForm' has no initializer and is not definitely assigned in the constructor.       
  15     myForm : FormGroup;
           ~~~~~~
 src/app/contact-form/contact-form.component.ts:17:10 - error TS2565: Property 'myForm' is used before being assigned.
    
 17     this.myForm.valueChanges.subscribe(console.log);
5 Answers

The error is connected with TypeScript's strictPropertyInitialization. It might be fixed the following way:

  myForm: FormGroup = this.fb.group({
    name: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50)])],
    email: ['', Validators.compose([Validators.required, Validators.email])],
    gender: ['', Validators.required],
    terms: ['', Validators.requiredTrue]
  });

  constructor(private fb: FormBuilder) { }

(Realisation is taken from the Angular's Reactive Forms Guide, they provide live example there and that's how they do it in profile-editor.component.ts)

add this to your code: // @ts-ignore , like that:

// @ts-ignore
editForm: FormGroup;

myForm: FormGroup;

Just move

   this.myForm.valueChanges.subscribe(console.log)

After form creation

   this.myForm = this.fb.group 

Because you try to subscribe for form before it creation

  createForm() {
  this.myForm = this.fb.group({
    name: ['', Validators.compose([Validators.required, Validators.minLength(3), 
Validators.maxLength(50)])],
    email: ['', Validators.compose([Validators.required, Validators.email])],
    gender: ['', Validators.required],
    terms: ['', Validators.requiredTrue]
     });

this.myForm.valueChanges.subscribe(console.log)   }

You should move the createForm() code inside the constructor of the component. Before you do this this.myForm.valueChanges.subscribe(console.log);

Ideally you should have the form creation in constructor and keep your subscriptions in ngOninit()

Related