I am trying to create a Reactive form in an Angular (v12) and Ionic (v6) project. When I submit the form, rather than call the submit function specified in the form tags ngSubmit property, the page just appears to refresh. The application is based on ionic tabs in case that could be causing an issue? I have imported the ReactiveFormsModule into the the page module rather than the app module, as the various tutorials I have read advise you need to do this when using with Ionic.
profile.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { ProfilePage } from './profile.page';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
CommonModule,
IonicModule,
FormsModule,
ReactiveFormsModule,
],
declarations: [ProfilePage]
})
export class ProfilePageModule {}
profile.page.ts
import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import { Profile } from '../shared/models/profile';
import { ProfileService } from './profile.service';
@Component({
selector: 'app-profile',
templateUrl: './profile.page.html',
styleUrls: ['./profile.page.scss'],
})
export class ProfilePage implements OnInit {
profileForm : FormGroup
constructor(private _profileService: ProfileService) {}
ngOnInit(): void {
this.profileForm = new FormGroup({
firstName: new FormControl(),
middleName: new FormControl(),
lastName: new FormControl(),
dob: new FormControl(),
companyId: new FormControl()
});
}
save() {
console.log('test');
}
}
profile.page.html
<ion-content>
<form [formGroup]="profileForm" (ngSubmit)="save()" novalidate>
<ion-list>
<ion-item>
<ion-label>First Name</ion-label>
<ion-input
id="firstName"
type="text"
required
formControlName="firstName">
</ion-input>
</ion-item>
<ion-item>
<ion-label>Middle Name</ion-label>
<ion-input
id="middleName"
type="text"
formControlName="middleName">
</ion-input>
>
</ion-item>
<ion-item>
<ion-label>Last Name</ion-label>
<ion-input
id="lastName"
type="text"
formControlName="lastName">
</ion-input>
>
</ion-item>
<ion-item>
<ion-label>DOB</ion-label>
<ion-input
id="dob"
type="date"
formControlName="dob">
</ion-input>
>
</ion-item>
<ion-button form="profileForm"
expand="block"
type="submit"
[disabled]="!profileForm.valid">
Save
</ion-button>
</ion-list>
</form>
</ion-content>
CodePudding user response:
Introduce it with Button Properties:
This worked and stopped the whole page from reloading:
as <button type="button"
or
- I changed the button type from "submit" to "button"
- I introduced a (click)= submitValues() inside the button props like this : submit
i.e. <button type="submit" (click)= submitValues()>Submit Form</button>
This stopped the page from reloading, I hope this helps.
CodePudding user response:
I managed to fix this by importing profile.module.ts into the AppModule.