I have set up a template-based form in Angular that utilizes Bootstrap (v4) for styling. My goal is to display validation messages upon form submission.
Here is an example of my form:
<form [ngClass]="{'was-validated': wasValidated}">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" [(ngModel)]="category.name" #name="ngModel" required maxlength="100"/>
<div *ngIf="name.invalid" class="invalid-feedback">
<div *ngIf="name.errors.required">
Name is required.
</div>
</div>
</div>
<button type="submit" class="btn btn-success" (click)="save()">Save</button>
</form>
Here is the structure of my component:
category: Category;
wasValidated: boolean = false;
ngOnInit() {
this.reset();
}
save() {
this.wasValidated = true;
this.categoriesService.createCategory(this.category).subscribe(
() => {
this.notificationService.add(notifications.category_saved, {name: this.category.name});
this.reset();
},
() => this.notificationService.add(notifications.save_category_failed)
);
}
reset() {
this.wasValidated = false;
this.category = {} as Category;
}
While this approach works, I feel it may be overly complex. I am seeking the most efficient way to implement this functionality.
Please note that the class was-validated
must be added to the form element to display the invalid-feedback
div. You can refer to Bootstrap's validation documentation here: https://getbootstrap.com/docs/4.0/components/forms/#validation
Additionally, I currently do not have a mechanism in place to prevent form submission if there are errors. Any suggestions on how to achieve this would be greatly appreciated!