The variable 'myForm' is missing an initializer in the constructor and has not been explicitly assigned a value

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]
        });
    }

}

An Issue Detected!

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);

Answer №1

The issue is related to TypeScript's strictPropertyInitialization feature. A possible solution is as follows:

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) { }

(This implementation is referenced from Angular's Reactive Forms Guide, where you can find a live example. This code snippet is extracted from profile-editor.component.ts file)

Answer №2

Here is a code snippet that you can add to your file with TypeScript:

// @ts-ignore
editForm: FormGroup;

myForm: FormGroup;

Answer №3

The updated default angular template now enforces the use of strictPropertyInitialization by setting it to true in the tsconfig file.

There are two options available:

  • Follow the recommended practice of initializing properties either inline or in the constructor
  • Alternatively, you can choose to disable the strictPropertyInitialization flag in your tsconfig file (although this is not advised)

Additional information can be found here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization

Answer №4

Implementing the non-null assertion operator can effectively avoid type checker errors in this scenario.

myForm!: FormGroup;

Answer №5

Just make a simple adjustment

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

Following the creation of the form

   this.myForm = this.fb.group 

Ensure you subscribe to the form after it has been created

  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)   }

Answer №6

Consider relocating the createForm() code to the constructor of the component. Prior to this, make sure to include

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

It is recommended to initialize the form in the constructor and manage your subscriptions within ngOnInit()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a Typescript error while trying to implement a custom palette color with the Chip component in Material-UI

I have created a unique theme where I included my own custom colors in the palette. I was expecting the color prop to work with a custom color. I tested it with the Button component and it performed as expected. However, when I attempted the same with the ...

Determine the class for a div within *ngFor by evaluating a condition

I am facing an issue where I need to dynamically assign a class to a div element within a *ngFor loop based on a method. Below is the code snippet from my HTML file: <ng-container *ngFor="let data of totalData let j = index"> < ...

Creating a FormGroup dynamically using an observable: A step-by-step guide

My current project involves creating a page with multiple reactive forms, tailored for different countries. These forms are generated based on JSON arrays received from the backend, allowing users to view and update settings individually. As I am uncertain ...

Imitate dependencies using Mocha and Typescript

In my typescript project, I am using mocha. Let's consider two modules: // http.ts export class Http { } // app.ts import Http from './http'; export class App { } I want to know how to mock the Http module while testing the App. The te ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. ...

I'm puzzled as to why the banner text for my three images in the slider is only displaying on one of the images, all crammed together

Currently, I am working on an ecommerce project with Next.js. One of the challenges I faced was while setting up my banner page that includes a react-slick slider for images. Initially, when I added just one image, I noticed multiple renderings of it, but ...

Conditioning types for uninitialized objects

Is there a way to create a conditional type that can determine if an object is empty? For instance: function test<T>(a: T): T extends {} ? string : never { return null } let o1: {} let o2: { fox? } let o3: { fox } test(o1) ...

Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end. function findDateDifferences(obj1, ...

Printing a JSON array in Angular: A step-by-step guide

Take a look at this Stackblitz example https://stackblitz.com/edit/angular-parse-object Response format received from REST API is [{"id":123,"name":Test,"value":{"pass": true, "verified": true}}, {"id":435,"name":Test12,"value":{"pass": false, "verified" ...

Having trouble resolving React within the Formik/dist package due to a custom webpack configuration

Struggling to set up projects from scratch, encountering an issue with webpack not being able to resolve formik's modules while other third-party modules like styled-components work fine. I've tried searching online for a solution but couldn&apos ...

Tips for sorting through the state hook array and managing the addition and removal of data within it

Having trouble finding a solution for filtering an array using the React useState hook? Let me assist you. I have declared a string array in useState- const [filterBrand, setFilterBrand] = useState<string[]>([]); Below is my function to filter this ...

Having difficulty transferring data between components using @Input syntax

I am having trouble passing the FailedProductId from Component1 to Component2 using @Input. Below is the code snippet: export class Component1 implements OnInit { public FailedProductId="produt"; constructor(private employeeService: ProductService) {} ...

"Exploring the process of creating a custom type by incorporating changes to an existing interface

One of the challenges I'm facing is defining an object based on a specific interface structure. The interface I have looks like this: interface Store { ReducerFoo : ReducerFooState; ReducerBar : ReducerBarState; ReducerTest : ReducerTestSt ...

"Comparing JSON objects can be done by checking if their IDs match, and if they do, assigning the value to another object

I am working with two sets of data var JSON_Categories = '[{ "id" : "1", "text" : "Category A"}, { "id" : 2, "text" : "Category B" }]'; var JSON_Article = '[{ "id&quo ...

Launch a modal window that displays a form generated using ngx-formly, which is nested within another form also created with

I have been utilizing ngx-formly to generate Angular forms dynamically from JSON data, and it has been working smoothly. One interesting scenario I encountered involves a custom button on a form that needs to open a modal dialog containing another form upo ...

Tips for sorting an array of objects by multiple keys while maintaining the order of each key that comes before

I am looking to create a versatile function that can organize an array of objects based on specified keys, while maintaining the order of previous keys. Here is a sample scenario: const input = [ { a: 'aardvark', b: 'bear', c: 'c ...

Adding a datepicker popup to an input field in angular2 with the format of YYYY-MM-DD hh:mm:ss is as simple as following

Can someone help me with adding a datepicker popup to an input field in Angular, using the format YYYY-MM-DD hh:mm:ss? I have tried the following code in my .html file but it doesn't seem to be working. <input [(ngModel)]="date2" ngui-datetime-pi ...

Display JSON element in Angular only once

Below is the code snippet: <ion-content padding> <h1>Datum: </h1> <ion-list> <ion-item *ngFor="let u of tecaj"> <h2>{{u.datum}}</h2> <h2>{{u.drzava}} | {{u.valuta}}</h2> ...

Mastering Data Labels in ng2-chart: A step-by-step guide

Once again, I find myself battling my Angular and JavaScript challenges, each question making me feel a little less intelligent. Let me walk you through how I got here. In my most recent project, I wanted to enhance the user experience by incorporating sl ...

Having trouble resolving the TypeScript error stating that "@types/express-serve-static-core/index has no exported member"? Here's how you

Encountering errors after upgrading node from version 14.18.0 to 20.16.0: ../node_modules/@types/express/index.d.ts node_modules/@types/express-serve-static-core/index"' has no exported member 'CookieOptions' node_modules/@types/express ...