Angular form submit not woking

Viewed 13263

Please help my angular form (submit) not working. I am making a login app and I am also a beginner to angular. Please help me in finding the problem.

login.component.html

<form (submit)="loginUser($event)">
  <input type="text" placeholder="Enter Username">
  <input type="password" placeholder="Enter Password">
  <input type="submit" value="Submit">
</form>

login.component.ts

import { Component, OnInit } from '@angular/core';

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

  constructor() { }

  ngOnInit() {
  }

  loginUser(event) {
    event.preventDefault()
      Console.log(event)
  }

}
4 Answers

I suggest you using angular componets for forms like ReactiveForms for example:

import { FormGroup, FormControl, Validators } from '@angular/forms';

  public loginForm: FormGroup;

  constructor() {
    this.loginForm = new FormGroup({
      'username': new FormControl('', [
        Validators.required
      ]),
      'password': new FormControl('', [
        Validators.required
      ])
    });
  }

  public sendLogin(): void {
    console.log(loginForm.value);
  }

<form [formGroup]="loginForm" (ngSubmit)="loginForm.valid && sendLogin()">
  <input formControlName="username" type="text" placeholder="Enter Username">
  <input formControlName="password" type="password" placeholder="Enter Password">
  <input type="submit" value="Submit">
</form>

Just remember importing import { FormsModule, ReactiveFormsModule } from '@angular/forms'; to your app.module.ts!

Angular comes with mainly two different ways of building forms in our applications. They are : 1. Template driven approach which allows to build forms with less cpde 2. Reactive approach using low level APIs which makes our forms testable without DOM. We can also use FormBuilder which is a high level API and is accessible to us in angular.

If you want to use the template driven approach. You need to first import the FormsModule in your app.module.ts file. Add the following statement in the file: import { FormsModule } from '@angular/forms'; and in your @NgModule directive, add the FormsModule;

  @NgModule({ 
    imports:[
        //other imports
        FormsModule
        ],
    })

Then in your login template, you need to make changes and the code should look like the following:

<form (ngSubmit)="loginUser($event)">
  <input type="text" placeholder="Enter Username" id="username">
  <input type="password" placeholder="Enter Password" id="password">
  <button type="submit">Submit</button>
<form>

// It is good to be semantic and use buttons instead of input type = "submit"

and In login.component.ts remove the event.preventDefault(). and also, the syntax for console.log is with small 'c'. So, the code would look like this:

import { Component, OnInit } from '@angular/core';

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

export class LoginComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  loginUser(event) {
      console.log(event);
  }
}

//You do not need to add event.preventDefault() since you won't be redirected to any new URL.

Now you can see in console, that your event is being logged.

If you want to try the reactive approach (which is also called model driven). You will need to import the ReactiveFormsModule. So, add the following snippet of code to the app.mopdule.ts

import { ReactiveFormsModule } from '@angular/forms'

@NgModule({
    imports:[
    //other imports
    ReactiveFormsModule
    ],
})

Remember, Reactive approach means you will need to model the form beforehand and implement in your template. So, in your login.component.ts. you will need to import FormControl to set the initial value for the form. Your login.component.ts file would look like this:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

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

  loginForm = new FormGroup({
  username: new FormControl(''),
  password: new FormControl('')
  });

  constructor() { }

  ngOnInit() {
  }

  loginUser() {
      console.log(this.loginForm.value);
  }

}

Now, Make changes to your login.component.html file to be the following:

<form [formGroup]="loginForm" (ngSubmit)="loginUser()">
  <input type="text" placeholder="Enter Username" formControlName="username">
  <input type="password" placeholder="Enter Password" formControlName="password">
  <button type="submit">Submit</button>
</form>

Now you can see your console to see the values being stored.

There are 2 things you need to do to make work. 1. Angular forms do not work without the name attribute in the input. You can change your code as below.

<input type="text" name="username" placeholder="Enter Username">

This is however not specific to angular but to HTML in general. see MDN description for name attribute

  1. You also need to make sure that FormsModule is imported in your angular module (most probably app.module.ts). Then in the form tag

Angular contains 2 ways to manage forms - FormsModule and ReactiveFormsModule. FormsModule is the easier of the two but does not provide a lot of control. ReactiveFormsModule is the is a bit complicated but provides a lot control. For your case FormsModule looks to be good enough.

Also, a more semantic way to create button is using the <button type="submit>" tag instead of <input type="submit">.

can you try this? Please use ngSubmit instead of using (submit).

<form (ngSubmit)="loginUser($event)">

You may want to add semicolons here to prettify your code

 event.preventDefault();
  Console.log(event);

some reference here: https://angular.io/guide/forms

Related