Consider utilizing reactive forms in your application. By grouping your controllers within a form group and applying validators to each controller, you can ensure that users cannot submit form data without completing all required fields. To handle this, check the validity of the form data in the OnSubmit function and halt the data processing if necessary.
For more information, refer to these resources:
Reactive Forms Angular
Form Validation Angular
Below is an example implementation:
export class AppComponent implements OnInit {
registerForm: FormGroup;
submitted = false;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
});
}
onSubmit() {
this.submitted = true;
// Halt execution if form is invalid
if (this.registerForm.invalid) {
return;
}
// Process data after validating the form
}
}
Corresponding HTML Code:
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>First Name</label>
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
<div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
<div *ngIf="f.firstName.errors.required">First Name is required</div>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.lastName.errors }" />
<div *ngIf="submitted && f.lastName.errors" class="invalid-feedback">
<div *ngIf="f.lastName.errors.required">Last Name is required</div>
</div>
</div>
</div>
</form>