If you're looking to register a user, check out this implementation where I utilize a service to handle the response and display any errors using toast messages.
export class RegisterPage implements OnInit {
resgiterForm: FormGroup;
submitted: boolean = false;
constructor(
private formBuilder: FormBuilder,
public navigation: NavigationPageAndParamsService,
public userService: UserService,
public toastController:ToastController
) {}
ngOnInit() {
this.resgiterForm = this.formBuilder.group({
username: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]],
});
}
get f() {
return this.resgiterForm.controls;
}
async register() {
console.log('Registration information:', this.resgiterForm);
this.submitted = true;
if (this.resgiterForm.invalid) {
return;
}
this.userService.registerUser(this.resgiterForm.value).subscribe(
data => {
console.log('Data', data);
if (data) {
this.navigation.navigateToPage('/tabs/feeds');
}
},
async err => {
var errMsg = err.error[0].message;
const toast = await this.toastController.create({
message: errMsg,
duration:3000,
position:'bottom',
cssClass:'registration-toast'
})
await toast.present()
}
);
}
}
<form [formGroup]="resgiterForm" (submit)="register()">
<ion-list>
<ion-item class="ion-padding-end ion-padding-start">
<ion-label position="stacked">Username*</ion-label>
<ion-input type="text" formControlName="username" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.username.errors }">
</ion-input>
</ion-item>
<div *ngIf="submitted && f.username.errors" class="invalid-feedback">
<div *ngIf="f.username.errors.required">Username is required</div>
</div>
<ion-item class="ion-padding-end ion-padding-start">
<ion-label position="stacked">Email*</ion-label>
<ion-input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }">
</ion-input>
</ion-item>
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.email">Email must be a valid email address</div>
</div>
<ion-item class="ion-padding-end ion-padding-start">
<ion-label position="stacked">Password</ion-label>
<ion-input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }"></ion-input>
</ion-item>
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
<div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
</div>
</ion-list>
<ion-list class="ion-text-center ion-padding-vertical">
<ion-button type="submit" shape="round">Submit</ion-button>
</ion-list>
</form>