Encountering dual TypeErrors while attempting to implement a login form with ReactiveFormsModule

Using Angular 11, I am facing an issue while creating a login form with ReactiveFormsModule. Upon loading the login page, a TypeError is displayed in the browser console. Additionally, after typing something in the input field, another TypeError appears. https://i.sstatic.net/XxMkB.png

Despite searching extensively for a solution and attempting all suggestions from others who have faced the same problem, I have not been able to resolve it. Having only started learning Angular a month ago, I suspect that I might be making a mistake somewhere but I am unable to pinpoint it.

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup} from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/core/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  form: FormGroup;

  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
    private router: Router
  ) {
    this.form = this.fb.group({
      email: [''],
      password: ['']
    })
  }

  ngOnInit(): void {
  }

  submitHandler(): void {
    const data = this.form.value;

    this.authService
      .login(data)
      .subscribe({
        next: () => {
          this.router.navigate(['/']);
        },
        error: (err) => {
          console.error(err);
        }
      })
  }
}

login.component.html

<section class="login-wrapper">
    <form formGroup="form" class="login-form" (ngSubmit)="submitHandler()">
        <article class="login-body">
            <h1>Login</h1>
            <input name="email" type="text" placeholder="E-mail" formControlName="email">
            <input name="password" type="password" placeholder="Password" formControlName="password">
            <button type="submit">Login</button>
            <p>Don't have an account? <a href="/signup">Sign up</a></p>
        </article>
    </form>
</section>

user.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SignUpComponent } from './sign-up/sign-up.component';
import { LoginComponent } from './login/login.component';
import { UserRoutingModule } from './user-routing.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    SignUpComponent,
    LoginComponent
  ],
  imports: [
    CommonModule,
    UserRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ]
})
export class UserModule { }

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { CoreModule } from '../app/core/core.module';
import { HeaderComponent } from '../app/core/header/header.component';
import { FooterComponent } from '../app/core/footer/footer.component';
import { HomeComponent } from './home/home.component';
import { UserRoutingModule } from '../app/user/user-routing.module';
import { UserModule } from './user/user.module';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    CoreModule,
    UserRoutingModule,
    UserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [
    AppComponent,
    HeaderComponent,
    FooterComponent
  ]
})
export class AppModule { }

Answer №1

Don't forget to enclose formGroup in brackets in your form HTML:

<form [formGroup]="form" class="login-form" (ngSubmit)="submitHandler()">

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

What is the best way to specify the data type of a value within a map in TypeScript?

I need assistance defining the value of a key in a map as a key-value pair in TypeScript. map: { key: someStruct } Is it possible to declare the type of someStruct and initialize it simultaneously? What is the best approach for accomplishing this? ...

Challenges in implementing Angular's guard correctly

I have a simple task that I'm struggling with - creating a guard to protect a route from all users except those with an "admin" role. To check this, I send a request to my API server with the user's API token. The server then responds with eithe ...

Tips for resolving the <!--bindings={ "ng-reflect-ng-for-of": "" }--> bug

Just starting out with Angular and I am having some issues with event binding and property binding in my game-control component. I have a button that, when clicked, adds numbers to an array using setInterval method. I am also passing data between compone ...

Issues with NPM start arise moments after incorporating create react app typescript into the project

I've encountered an error while trying to initiate my create react app with Typescript. Despite following all the necessary steps, including adding the .env file (with SKIP_PREFLIGHT_CHECK=true) and updating/reinstalling NPM, I keep facing this issue. ...

Angular's GET request response is returning an "Undefined" value instead of the

As an Angular beginner, I've successfully set up and tested a service that retrieves data from a JSON file using the Get method. However, when attempting to access the data inside the JSON file, it returns as undefined. My goal is to use this data as ...

How can I properly test an Angular pipe that has its own dependencies, which are injected using NG 15 inject()?

For a basic demonstration, within a fresh Angular 15 CLI application: We need to create a new service called HelperService This service will be injected into DemoPipe with the newly introduced inject() method: export class DemoPipe implements PipeTransfo ...

Is it advisable to prevent Set and Map from having unspecified generics in TypeScript?

Upon reviewing some old code that I wrote, I realized that I had neglected to specify a generic type for a Set. The type was set as Set<unknown>. Strangely, despite this, I found that I could still utilize all the methods of the Set without encounter ...

Issue with Angular 2 Routing: Unable to find a matching route

Currently, I'm in the process of developing an Angular 2+ application that requires routing. One of the requirements is for the color scheme of the entire app to change based on a URL parameter input. In my app.module.ts file, I have the following co ...

Angular route unable to detect Passport User Session

The navigation bar in the header features buttons for Register, Login, and Become a Seller. Upon user login, it displays logout and view profile buttons. This functionality is operational on all routes except one, causing a client-side error. user not def ...

Exploring TypeScript and React Hooks for managing state and handling events

What are the different types of React.js's state and events? In the code snippet provided, I am currently using type: any as a workaround, but it feels like a hack. How can I properly define the types for them? When defining my custom hooks: If I u ...

Angular 11 error: Datatable type is not defined

We have a services.ts file that requires 2 arguments. UPDATE: It appears that I was looking at the error incorrectly. This method is causing the console error: private checkLink(row, options) { if (options.type === 'link' || options.type ...

Several mat-table components are displayed on a single page, with each table equipped with its own loading spinner to indicate network activity

Currently, I am encountering a problem while trying to display multiple mat-tables (any number of tables) and I need a spinner to be shown whenever there is a network request for data on a particular table. The loader should only appear in that specific ...

Activate the onclick event for HTML select-options when there is only a single option available

My HTML select dropdown features 5 options, which are a list of car manufacturers. When a user clicks on an option, the onchangeHandler triggers to capture the selected value. Based on this selection, another dropdown displaying car models is shown to the ...

Alert: Circular dependency identified: Unable to determine the module

During the development of our project, we encountered an issue: fail: Microsoft.AspNetCore.SpaServices[0] WARNING in Circular dependency detected: fail: Microsoft.AspNetCore.SpaServices[0] src\app\app.module.ts -> src\m ...

JQuery value does not transfer to Angular 2 textarea

My Angular 2 application features an input textarea field: <textarea id="projectDescription" required [(ngModel)]="projectDescription" [formControl]="createNewForm.controls['projectDescription']" style="margin-bottom:-2%;width:50%;"></t ...

Angular form grouping radio buttons in a unique way

Encountering some unusual behavior with radio buttons and forms currently. In my form, I have 4 radio buttons set up. The issue I'm facing is that when I click on a radio button, it remains enabled permanently. This means I can have all 4 options sel ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

Guide on Validating Several Email Addresses in a React Form using Angular 4

I need to input 50 email addresses with the same domain name (gmail.com). Currently, I am using a Reactive form but the code I have implemented is not working as expected. https://stackblitz.com/edit/angular-wfwfow If anyone could assist me with this, I ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...