The absence of definition for onSubmit is causing an issue in Angular 6

I am encountering an issue with validating the sign-in form as it is showing an error stating onSubmit is not defined. Below is the code snippet:

import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-customer-signin',
  templateUrl: './customer-signin.component.html',
  styleUrls: ['./customer-signin.component.css']
})
export class CustomerSigninComponent implements OnInit {
   customerSigninForm: FormGroup;

  constructor() {}

  ngOnInit() {
   this.customerSigninForm = new FormGroup({
       'email': new FormControl(null, [Validators.required, Validators.email], this.forbiddenEmails),
       'pwd': new FormControl(null, [Validators.required,
       Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&].{8,}')
        ]);
     });

  onSubmit() {
    console.log(this.customerSigninForm);
    this.customerSigninForm.reset();
  }
}

}

Here is the HTML segment:

<form action="" [formGroup]="customerSigninForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
            <input _ngcontent-c0="" class="form-control form-control-lg" placeholder="email" type="text" id="email" formControlName="email"/>
            <span *ngIf="!customerSigninForm.get('email').valid && customerSigninForm.get('email').touched" class="help-block">Please enter a valid email!</span>
        </div>
        <div class="form-group">
            <input class="form-control form-control-lg" placeholder="Password" type="password" formControlName="pwd"/>
            <span *ngIf="!customerSigninForm.get('pwd').valid && customerSigninForm.get('pwd').touched" class="help-block">Please enter a valid password!</span>
        </div>
        <div class="form-group">
            <div class="extra-btns align-items-center">
                <button class="btn btn-link ">Forget Password</button>
                <button class="btn btn-link ">Forget Password</button>
            </div>
            <div>
                <span
          *ngIf="!customerSigninForm.valid && customerSigninForm.touched"
          class="help-block">Please enter valid data!</span>
                <button type="submit" class="  btn form-btn btn-lg btn-block">Sign In With Email</button>
                      </div>
        </div>
    </form>

What could be causing this error? I have researched similar examples online and they seem to match my implementation. I have ensured there are no spelling errors since onSubmit is consistent in both the HTML and TypeScript files. How can I resolve this issue?

Answer №1

Make sure to define the onSubmit function outside of the ngOnInit function block. For more information, refer to angular-lifecycle-hooks

Here's an example:

ngOnInit() {
   this.customerSigninForm = new FormGroup({
       'email': new FormControl(null, [Validators.required, Validators.email], this.forbiddenEmails),
       'pwd': new FormControl(null, [Validators.required,
       Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&].{8,}')
        ]);
     });
}

onSubmit() {
    console.log(this.customerSigninForm);
    this.customerSigninForm.reset();
}

Answer №2

It is advisable to place your onSubmit() function outside of the ngOnInit().

For instance, you can structure it like this:

ngOnInit(){
   // Do something 
}
OnSubmit(){
   // save data 
}

This setup has proven effective for me, and I believe it will work well for you too.

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

Unexpected disappearance of form control in reactive form when using a filter pipe

Here is a reactive form with an array of checkboxes used as a filter. An error occurs on page render. Cannot find control with path: 'accountsArray -> 555' The filter works well, but the error appears when removing any character from the fi ...

After clicking on the "Delete Rows" button in the table, a white color suddenly fills the background in Angular Material

When the dialog box pops up, you'll see a white background color: https://i.stack.imgur.com/EflOx.png The TypeScript code for this action can be found in config-referrals.component.ts openDialog(action, obj) { this.globalService.configA ...

There seems to be an issue with the Typescript version compatibility in the node_modules folder for the Angular Material table cell component

While working on my project with Angular, I encountered an issue. I attempted to downgrade my TypeScript version to 3.9.7 but the problem persists. Below are the dependencies listed in my package.json: "private": true, "dependencies&qu ...

Unable to establish a connection between the HTML element and the TypeScript variable

I'm facing an issue with my code where the function that worked perfectly for register and login is not functioning properly on the index page. Even though there seems to be no errors in the login and register functions, I have a form with an input s ...

Cannot establish a connection with Socket.IO

I've encountered an issue with establishing a connection to Socket.IO in my node server. Although the server starts successfully with Socket.IO, I am not seeing any console logs when trying to connect to Socket. this.server.listen(this.port, () => ...

Error occurs when the directive is not being applied due to the usage of the "attr" host attribute

Referring to a post about host attributes, I have developed a Plunker for demonstration purposes. Upon reviewing the github issue, it seems that using [attr.someDirective] should allow us to selectively apply a directive attribute to an element. Although ...

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...

Encountering an error from the Angular CLI compiler can be frustrating, but fear not! By making a simple change (that can always

When I was compiling my app for the first time using ng serve I encountered this error: img error However, when I made a change to one of the comp files (it could be any file), and webpack recompiled it with Angular CLI - everything worked fine. I sus ...

Utilizing Material Design Icons within Angular 4: A Step-by-Step Guide

I'm looking to integrate the icons available on into my angular 4 project. However, the website's instructions only cover how to do this in Angular 1.x () Can someone guide me on how to include Material design icons so that I can use them like ...

The error message indicates a change in the binding value within the template, resulting in an

This is the structure of my component A : <nb-tab tabTitle="Photos" [badgeText]="centerPictures?.pictures?.length" badgePosition="top right" badgeStatus="info"> <app-center-pictures #centerPictures [center]="center"> ...

Enhance Your SVG Elements with Angular Tooltips

I am faced with a challenge on my website where I have an SVG element: <ellipse id="svg_2" cy="78.999999" cx="1042.499999" stroke-width="1.5" stroke="#000" fill="#fff"/> My goal is to add a tooltip to this specific element. I attempted using NGPrim ...

Tips on how to confirm that the content of the angular form begins and concludes with a specific string

For user input that must start with a specific string, such as XYZ, have business data in between, and end with ENDXYZ within a textview, I am utilizing the Angular framework for the UI. <div class="mb-3 col-md-5"> <label for=&qu ...

Angular - Facing issues with CORS for every request made

Currently, I am developing an angular 12 application for my university with a java back-end. While testing Angular's http client, I encountered an issue where CORS is blocking my requests. const API_URL = 'http://localhost:9080' @Injectable ...

Is it possible to easily organize a TypeScript dictionary in a straightforward manner?

My typescript dictionary is filled with code. var dictionaryOfScores: {[id: string]: number } = {}; Now that it's populated, I want to sort it based on the value (number). Since the dictionary could be quite large, I'm looking for an in-place ...

Angular 12: Running ng test shows code coverage error - TypeError: Unable to access 'initialize' property as undefined

I encountered an error in the code coverage console: TypeError: Cannot read properties of undefined (reading 'initialize') I am trying to call a service method from the component.ts file The code in the component.ts file looks like: this.myAuth ...

VS Code is throwing an Error TS7013, while Typescript remains unfazed

In my Typescript/Angular project, I have the following interface: export interface MyInterface { new (helper: MyInterfaceHelpers); } After compiling the project, no errors are shown by the Typescript compiler. However, VSCode highlights it with squiggl ...

TSLint warning: Duplicate identifier detected - 'err'

Currently facing an issue with tslint displaying the following error Shadowed name: 'err' Providing the code snippet for reference fs.readdir(fileUrl, (err, files) => { fs.readFile(path.join(fileUrl, files[0]), function (err, data) ...

Issue arises when monitoring the clean state of a form within a reactive Angular form

Here is a StackBlitz example showcasing the editor in a reactive form. I have set up registration and subscription to changes on the form. Initially, when the form is loaded, making changes in the editor triggers the change function. However, after clickin ...

Avoiding the use of reserved keywords as variable names in a model

I have been searching everywhere and can't find a solution to my unique issue. I am hoping someone can help me out as it would save me a lot of time and effort. The problem is that I need to use the variable name "new" in my Typescript class construct ...

Component fails to navigate to the page of another component

Hello there. I am facing an issue where the button with routelink in the RegistrationComponent is not routing to the page of LogInComponent and I cannot figure out why. Angular is not throwing any errors. Here is the RouteComponent along with its view: im ...