Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular form submit not submitting

Please help my angular form (submit) not working. I am making a login app

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)
  }

}
like image 497
Rajvir Singh Avatar asked Jun 04 '26 16:06

Rajvir Singh


1 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!

like image 153
Alejandro Meza Avatar answered Jun 06 '26 06:06

Alejandro Meza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!