angularangularjsangularjs-ng-form

angular ngSubmit doesnt work (button inside and module imported)


I'm a beginner with angular testing the framework for the first time.

I have a simple form

<form (ngSubmit)="onSubmit()">
   <label for="test">Test Prompt: </label>
   <input type="text" id="test" name="test">
   <button type="submit">Search</button>
</form>

and a component just made with ng generate:

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

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent {
  constructor(){}
  onSubmit() {
    alert('test');
    console.log('Form submitted successfully!');
  }
}

however nothing logs to the console and no alerts pop

I have also added the module in app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HomepageComponent } from './homepage/homepage.component';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    HomepageComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Solution

  • Adding an answer to better explain with minimal example.

    In your component:

    
    form = this.fb.group({});
    
    constructor(private fb: FormBuilder){}
    

    then in your template:

    <form [formGroup]="form" (ngSubmit)="...">
    
    

    Edit: Check out the Form Group Directive documentation here