Angular TS2564 Error: Attempting to access an uninitialized property 'formGroup'


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

  ngOnInit() {
    this.setupForm();
  }

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


  getErrorMessage(input) {
    switch (input) {
      case 'user':
        if (this.userForm.get('username').hasError('required')) {
          return 'Username is required';
        }
        break;
      case 'pass':
        if (this.userForm.get('password').hasError('required')) {
          return 'Password is required';
        }
        break;
      default:
        return '';
    }
  }

Creating login form in Angular application.

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

How can this error be resolved?

Answer №1

This pertains to the topic of strict initialization.

  1. Include ! to indicate that this is not initialized:
formGroup!: FormGroup;
  1. Add |undefined as an extra type :
formGroup: FormGroup | undefined

Answer №2

To avoid errors from the type checker, you can utilize the non-null assertion operator

 formGroup!: FormGroup;

Alternatively

Initialize the formGroup at the top level of your code

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

  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

Add a decorator to all functions in a TypeScript class to list all available methods

How can I apply a decorator function to all methods within a class in order to streamline the code like this: class User { @log delete() {} @log create() {} @log update() {} } and have it transformed into: @log class User { ...

Encountering a "subscribe is not a function" error while attempting to utilize a JSON file in Angular 2

My attempt to import a JSON file into my service is resulting in the following error: Error: Uncaught (in promise): TypeError: this._qs.getBasicInfo(...).subscribe is not a function(…) The current state of my service file is as follows @Injectable() ...

Guide to validating multiple form controls simultaneously in Angular 2

This is the primary form group: this.mainForm = this.formBuilder.group({ productType1: new FormArray([], CustomValidators.minSelectedCheckboxes()), productType2: new FormArray([],CustomValidators.minSelectedCheckboxes()), ...

Typescript does not support importing JSON files

I'm facing an issue with importing json files in a NodeJS v18 project. My setup includes TS 4.8.4 and the following configuration in tsconfig.json: "compilerOptions": { "esModuleInterop": true, "target": "esnext& ...

typescript React-Redux challenge: Boosting Your mapDispatchToProps Skills

I'm having trouble determining the type of my mapDispatchToProps function in the SignInComponent. See the code snippet below: Here is my authAction.ts file: import firebase from 'firebase/app' import { Dispatch } from 'react'; ty ...

Inject a dynamic component into an Angular 2 Modal Service

Struggling to dynamically insert a component into a custom modal window component. The modal component is given a URL to an HTML file containing a component: <a modal bodyUrl="/some/path/body.html"> body.html: <hello-component></hello-co ...

Learning how to toggle default snippet keywords on and off based on specific scenarios within the Angular Ace Editor

Within the Ace editor, I have incorporated custom snippets alongside the default ones. However, there are certain scenarios where I would like to exclusively display the custom snippets and hide the default ones. Is there a way to disable or conceal the ...

Tips for resolving the issue with the 'search input field in the header' across all pages in angular 5 with typescript

I currently have a search field in the header that retrieves a list of records when you type a search term and click on one of them. The search function utilizes debounceTime to reduce API requests, but I'm encountering an issue where the search doesn ...

Build an object using a deeply nested JSON structure

I am working with a JSON object received from my server in Angular and I want to create a custom object based on this data. { "showsHall": [ { "movies": [ "5b428ceb9d5b8e4228d14225", "5b428d229d5b8e4 ...

Guide on how to utilize query parameters in the redirectTo function

Looking to set up a redirect based on query parameters that lead to a specific page. For instance: /redirect?page=hero&id=1 This should direct to: /hero/1 Is there a way to achieve this in the route configuration? Maybe something like: { path: &ap ...

The Angular2 Renderer successfully renders the Svg rect element, but it is not displayed on the webpage

I am looking to generate a bar chart utilizing SVG with rectangles as the bars. Here is the relevant code: barchart-one.html <svg #svgone width="400" height="250" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 250"> <g #abcd>< ...

Creating intricate mazes using canvas drawing techniques

I recently developed a maze generator as a personal project utilizing a graph. While the generation logic works perfectly, I am facing challenges when it comes to rendering the maze. In my approach, each cell is represented by an array of 4 edges where the ...

What is the best way to obtain user-inputted data from a dynamic input table with dynamically added rows?

I am struggling to fetch the user-entered data from a dynamic inputs table. Each time a new row is added dynamically to the table, I have to create a new array in the component.ts file to retrieve the data using Two-way data binding. Below is the HTML cod ...

Setting the current time to a Date object: A step-by-step guide

Currently, I am working with a date input and storing the selected date in a Date object. The output of the date object looks like 2021-03-16 00:00:00. However, I want to update this date object's time part to reflect the current time. The desired ou ...

I am looking to replicate a DOM element using Angular 4

I am interested in creating a clone of a DOM element. For example, if I have the following structure: <div> <p></p> <p></p> <p></p> <p></p> <button (click)="copy()"></button> & ...

Increasing numbers using Vuex Module Decorators and TypeScript

I'm encountering a major challenge with incrementing data. @Module class Mod extends VuexModule { public value = 2; // facing multiple type errors when trying to access this.state.value within a MutationAction. @MutationAction({ mutate: [" ...

Angular - What is the best way to implement a model for a sophisticated object structure?

The object structure I'm dealing with in Angular is as follows: this.calendar = { "years": { 2018: { "months": 0: { "weeks": 1: { ...

When the data is not initialized within the ngOnInit() function, the p-dataTable does not bind properly

In the process of building a form, there is a specific dialog available for users to input data. The dialog functions within a larger form structure. Once the user finishes entering their data in the dialog and clicks on the SAVE button, the entered inform ...

What could be the root cause behind the error encountered while trying to authenticate a JWT?

I've been working on integrating a Google OAuth login feature. Once the user successfully logs in with their Google account, a JWT token is sent to this endpoint on my Express server, where it is then decoded using jsonwebtoken: app.post('/login/ ...

What could be causing the request parameter in my ag-grid to be undefined?

Currently experimenting with the ServerSide RowModel of Ag-Grid in combination with Angular. Planning to add server response later on, but for now focusing on familiarizing myself with the framework. Struggling to retrieve request parameter values from my ...