Issue: formGroup requires an input of type FormGroup. Please provide one; Error: Unable to access property 'controls' as it is undefined

In the process of building a login and registration form using Angular with .Net core, I encountered an error upon running the program. The error is showing up in the Browser Console tab.

This is my userlog.component.ts file:

import { Component, OnInit, Output , EventEmitter} from '@angular/core';
import { AccountService } from '../_services/account.service';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { AbstractControl, FormBuilder, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';



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


export class UserlogComponent implements OnInit {

  @Output() cancelRegister = new EventEmitter();
  registerForm: FormGroup;
  model: any = {};
  validationErrors: string[] = [];

  constructor(public accountService: AccountService, private fb: FormBuilder, private router: Router, private toastr: ToastrService) { }

  ngOnInit(): void {
    
  }

  intitializeForm() {
    this.registerForm = this.fb.group({
      username: ['', Validators.required],
      email: ['', Validators.required],
      password: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(15)]],
      confirmPassword: ['', [Validators.required, this.matchValues('password')]],
      firstname: ['', Validators.required],
      dob: ['', Validators.required]
    })
  }

  register() {
    this.accountService.login(this.registerForm.value).subscribe(response => {
      this.router.navigateByUrl('/dashboard');
    }, error => {
      this.validationErrors = error;
    })
  }

  matchValues(matchTo: string): ValidatorFn {
    return (control: AbstractControl) => {
      return control?.value === control?.parent?.controls[matchTo].value 
        ? null : {isMatching: true}
    }
  }

  login() {
    this.accountService.login(this.model).subscribe(() => {
      this.router.navigateByUrl('/dashboard');    
    }, error => {
      console.log(error);
      this.toastr.error(error.error);
      
    })
  }

  logout(){
    this.accountService.logout();
    this.router.navigateByUrl('/');
  }

  cancel(){
    this.cancelRegister.emit(false);
  }

  
}

This is my userlog.component.html file:

<div class="user signinBx">
    <div class="imgBx"><img src="assets/Images/maanavar.png" alt="" /></div>
    <div class="formBx">
    <form #loginForm="ngForm" class="form-inline my-2 my-lg-0" (ngSubmit)="login()">
        <h2>Sign In</h2>
            <!-- [(ngModel)] denotes component to html (click) html to component -->
        <input class="form-control mr-sm-2" type="text" name="username" placeholder="Username" [(ngModel)]="model.username" />
        <input class="form-control mr-sm-2" type="password" name="password" placeholder="Password" [(ngModel)]="model.password"/>
        <button [disabled]="!loginForm.valid" class="btn btn-success my-2 my-sm-0" type="submit">Login</button>
        <div>
            <p class="signup ml-3">
                Don't have an account ?
                <a href="#" onclick="toggleForm();">Sign Up.</a><br>   <br>
                <a class="text-danger" href="#">Not able to access ??</a>
            </p>
        </div>
        
    </form>
    </div>
</div>
<div class="user signupBx">
    <div class="formBx">
        <!-- if a forn is ngform then type submit inside the form calls ngsubmit -->
    <form [formGroup]="registerForm" (ngSubmit)="registerForm.valid && register()" autocomplete="off">
        <div class="form-group">
            <h2>Create an account</h2>
    
        
           <input class="form-control mr-sm-2" type="text"  placeholder="Username" [formControl]='registerForm.controls["username"]'/> 
        <input class="form-control mr-sm-2" type="email"  placeholder="Your E-Mail" [formControl]='registerForm.controls["email"]' />
        <input class="form-control mr-sm-2" type="password"  placeholder="Password" [formControl]='registerForm.controls["password"]' />
        <input class="form-control mr-sm-2" type="password"  placeholder="Confirm Password" [formControl]='registerForm.controls["confirmPassword"]' />
        <input class="form-control mr-sm-2" type="text" placeholder="Firstname" [formControl]='registerForm.controls["firstname"]'/> 
        <input class="form-control mr-sm-2" type="date"  placeholder="Date of Birth" [formControl]='registerForm.controls["dob"]'/> 
        
        <div class="row" *ngIf="validationErrors.length > 0">
            <ul class="text-danger">
                <li *ngFor="let error of validationErrors">
                    {{error}}
                </li>
            </ul>
        </div>
    
          
        <button [disabled]='!registerForm.valid' class="btn btn-success mr-2 my-sm-0" type="submit">Sign Up</button>  
        <button class="btn btn-danger my-sm-0" (click)="cancel()" type="button">Cancel</button>
        <p class="signup">
        Already have an account ?
        <a href="#" onclick="toggleForm();">Sign in.</a>
        </p>
        </div>
        
    </form>
    </div>
    <div class="imgBx"><img src="assets/Images/homeSignin.jpg" alt="" /></div>
</div>

</div>

I have attempted to solve this problem by researching similar issues without success. Can someone assist me with resolving this? Thank you.

Answer №1

To ensure the formGroup is properly created, it is important to call the initializeForm method within the ngOnInit lifecycle hook.

 ngOnInit(): void {
this.initializeForm();}

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

Can you choose to declare a type in TypeScript, or is it required for every variable

Has anyone encountered a problem similar to this? type B = a ? 'apple' | 'grape' | 'orange' : 'apple' | 'grape'; // This code results in an ERROR! const x = (a: boolean, b: B) => console.log('foo&a ...

Having trouble getting your custom Angular directive to work properly with interpolation?

One of the custom Angular directives I have developed accepts a couple of inputs. Its main purpose is to highlight the matching parts of the element to which the directive is attached with the input matchTerm. This directive is intended to be used with a t ...

No changes made to Observable when it's empty

I encountered an unusual issue with the rxjs "filter" in my development environment: SAP ComposableStorefront / Spartacus "~2211.21.0" angular 17.2.0 Currently, I am on a product detail page and applying a filter to my Observable in the following manner: ...

typescript/raven.d.ts, at line 205, is throwing an error stating that it cannot recognize the name 'unknown' when attempting to install npm in an Ionic

During my work on an ionic project, I encountered this error while attempting to run npm install. https://i.sstatic.net/yHc04.png You can access the package.json file through this link: ...

Angular 2 Change Detection Issue: Value of expression has been updated post-check. Original value: 'over'. Updated value: 'side'

I'm encountering an error specifically in Firefox, but not in Chrome or IE. "Error: Error in ./DefaultLayoutComponent class DefaultLayoutComponent - inline template:2:14 caused by: Expression has changed after it was checked. Previous value: ' ...

Angular 2 routing for dynamic population in a grid system

My website is compiling correctly, however, in the Sprint dropdown menu where I have set up routing... <a *ngFor = "let item of sprint;" routerLink = "/Summary" routerLinkActive = "active"> <button *ngIf = "item.Name" mat-menu-item sty ...

An effective way to retrieve a property from an observable by utilizing a pipe

I'm having trouble storing an OrderState object in my ngrx store and extracting data from it for my UI using the async pipe. Specifically, I want to retrieve a child property from this observable object. order.state.ts export interface OrderState { ...

Learn how to configure an Angular2 Template Driven form element by implementing two-way binding and integrating template driven form validation techniques

Can anyone help me figure out the correct way to set up an Angular template driven form element for both validation and two-way binding? I've tried using ngModel in different ways, but cannot seem to achieve two-way binding without encountering issues ...

What could be causing the OnInit lifecycle hook to fail to execute properly?

I'm having trouble with this code. Every time I run it, the console throws a type error saying it can't read property sort. Does anyone have any ideas on how to fix this? import { Component, OnInit, Input } from '@angular/core'; impor ...

Can you explain the significance of this particular line in the source code of VSCode?

While browsing through the VS Code source code, I stumbled upon the following snippet: https://github.com/microsoft/vscode/blob/5da4d93f579f3fadbaf835d79dc47d54c0d6b6b4/src/vs/workbench/contrib/comments/browser/commentsEditorContribution.ts#L166 It appear ...

Binary encounters an issue: Error - Module failed to self-register

Binary file saved to the specified directory Caching binary for future use [email protected] during postinstall node script execution. The system attempted to locate the relevant binary but encountered an error: Module did not self-register. This iss ...

Using a Class Decorator in Typescript to Enhance Static Methods across all Classes

Imagine having a class filled with numerous static methods. The objective is to encapsulate each static method within a function. The specific aim is to handle async errors by applying .catch to every static method in the following manner: // Within user-r ...

A guide on transforming a 1-dimensional array into a 2-dimensional matrix layout using Angular

My query revolves around utilizing Template (HTML) within Angular. I am looking for a way to dynamically display an array of objects without permanently converting it. The array consists of objects. kpi: { value: string; header: string; footer: string }[] ...

Issue in Typescript: The type 'RegExpMatchArray' cannot be assigned to a parameter of type 'string'

Here is the code snippet I am working with: import { persistState } from 'redux-devtools'; const enhancer = compose( applyMiddleware(thunk, router, logger), DevTools.instrument(), persistState( window.location.href.match(/[?&]debu ...

Releasing an ASP.NET CORE web application with AngularJS on IIS

In the process of developing a new asp.net core web app (using the full .net framework) with AngularJS version 1.5.8, we have encountered an issue. Our app is currently very basic, consisting of just one page displaying student data in a table. When runn ...

Learn the process of inserting a table in ExcelJS specifically for Angular applications

I encountered an issue when attempting to add a table with data. An error message stating "AddTable is not function" appeared. let workbook = new ExcelJS.Workbook(); let worksheet = workbook.addWorksheet("Data"); worksheet.addTable({ name: 'My ...

Tips for extracting images from an ion-img element when the source is a PHP script that generates a captcha code

For my college project, I am scraping a website to display the results. One issue I'm facing is that the results are protected by a captcha code. I attempted to scrape using a node HTML parser, but when I extracted the src attribute, it pointed to c ...

Angular Material Clock Picker for 24-Hour Time Selection

Struggling to find a time picker component that supports the 24-hour format for my Angular 14 and Material UI application. Can anyone help? ...

Issue arose when attempting to remove an item from an array within React

I have a handleAd function that adds new components to an array, and I also have a handleDelete function that is supposed to remove the selected element from the array. I am generating unique keys for each element to prevent deletion issues. Initially, th ...

Angular2 plugin for redacting content

I'm attempting to integrate Redactor with additional plugins, but I'm encountering an issue where the counter plugin displays 0 words and 0 characters after the page has loaded. { words: 0, characters: 0, spaces: 0 } To address this pro ...