MadDev
MadDev

Reputation: 113

Angular 14 forms onSubmit button doesn't work

I am newbie on Angular 14, and I am trying to call a simple onSubmit event, but... doesn't work, And to be honest I don't know why... I researched but I don't know what is the proper solution in terms of Angular 14.

Here is my code:

main-component.ts

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


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

 limitNumber: number;
 randomNumber: number;

constructor() {

 this.randomNumber = this.generateRandomNumberBetween1And100();
 this.limitNumber = this.generateEinsteinRandomNumber();

 }   

generateRandomNumberBetween1And100() {
   this.randomNumber = Math.floor(Math.random() * 100) + 1;
   return this.randomNumber;
}

 generateEinsteinRandomNumber() {   
   this.limitNumber = Math.floor(Math.random() * (100 - this.randomNumber)) + 
   this.randomNumber + 1;  
   return this.limitNumber;  
}


 onSubmit() {
   console.log("onSubmit");
   alert("onSubmit");
 }

}

main-component.html

<form (ngSubmit)="onSubmit()" >
<label>
  <span>Einstein number: </span>
  <input type="text" placeholder="Einsten random number" [value]="randomNumber">
</label>
<br>  
<label>
    <span>Limit number: </span>
    <input type="text" placeholder="Random limit number" [value]="limitNumber" >
  </label>    
  <br>
<button type="submit">Submit</button>
</form> 

So, when I click the Submit button de onSubmit() function doesn't works.

Any ideas?

Thanks in advance!

Upvotes: 0

Views: 558

Answers (1)

MadDev
MadDev

Reputation: 113

Well, It was an stupid error, but I think that could be positive for the community post the solution.

In the html code I wrote the form with the ngSubmit attribute, this is not correct.

<form (ngSubmit)="onSubmit()" >

The correct way is use just (submit) such an attribute. E.g.

<form (submit)="onSubmit()" >

It works!

Upvotes: 1

Related Questions