Learn the method of setting the 'was-validated' class on a form in order to display validation feedback messages dynamically using Angular 5 following form submission

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!

Answer №1

Thanks to the guidance provided by @Chellappan V, I was able to effectively implement the solution I was aiming for.

The changes I made include:

Firstly, I added #form="ngForm" to the form tag in the template. Secondly, I adjusted the ngClass expression to depend on the form's submitted state, rather than manually setting a boolean to true upon form submission. Lastly, I passed the form as a parameter in the submit method of the save button.

<form novalidate #form="ngForm" [ngClass]="{'was-validated': form.submitted}">
    <!-- form controls -->
    <button type="submit" class="btn btn-success" (click)="submit(form)">Save</button>
</form>

In the component, I used @ViewChild to access the template variable in the component.

@ViewChild("form")
private form: NgForm;

The submit method now accepts a form parameter of type NgForm, which is used to verify the form's validity before making a request to the backend:

submit(form: NgForm) {
    if (form.valid) {
        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)
        );
    } else {
        this.notificationService.add(notifications.validation_errors);
    }
}

Lastly, the reset method resets both the form and the model, allowing them to be re-entered for the next submission:

reset() {
    this.form.resetForm();
    this.category = {} as NewCategoryDto;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing Bootstrap's Radio Button Styles

I am having trouble customizing the style of radio buttons in Vue with Bootstrap-vue. Is it not possible to override the default style? Here is the design I want https://i.sstatic.net/xlOlY.png and here is how it currently looks https://i.sstatic.net/l1DF ...

The images on the Shopify platform are becoming increasingly fuzzy

I'm facing an issue where the images I add to my Shopify site using the Brooklyn theme appear blurry unless resized to a small scale. The dimensions of the images are 1748 x 1240 at 300dpi. My intention is to implement a JQuery image slider (lightsli ...

At what point are routed components initialized?

Here is a route setup I am working with: path: ':id', component: ViewBookPageComponent }, After adding this route, an error keeps popping up: Error: Cannot read property 'id' of null I haven't included a null check in the compo ...

Connecting an image to its corresponding content through hover effect

Can someone please assist me? I am trying to create a hover effect on an image with an "add to cart" link similar to what is shown here: I seem to be having trouble with the code, could you provide some guidance? .hunderter { background: url(http ...

centering headers using tailwind styles

I am facing a challenge with positioning my main title, logo, and subtitle. I want the subtitle to be centered regardless of the logo's width. Currently, the position of the sub title changes based on the logo's width, resulting in it not aligni ...

JavaScript functioning in Firefox but not Chrome

Here is the code snippet in question: $('#ad img').each(function(){ if($(this).width() > 125){ $(this).height('auto'); $(this).width(125); } }); While this code works correctly in Firefox, it seems to have i ...

Ways to conceal CSS on the page when triggering a different element

I am trying to achieve the functionality of hiding the black arrow when clicking on the green arrow, all without using jQuery. Here is my fiddle: http://jsfiddle.net/t5Nf8/195/ html: <div class="arrow-down"></div> <div class="arrow-up"> ...

Rearranging columns in Bootstrap 4 beta across multiple containers

Sorry for any language issues in my English. This shows my regular grid: ------------------------------- | A | B | C | ------------------------------- | D (horizontal menu) | ------------------------------- Is it possible to d ...

What is the best way to prevent <hr> from covering a <div> in CSS?

I'm currently facing a challenge in moving an <hr> element behind my div element. I have already tried positioning, but it didn't work as expected. The <hr> is still visible through the white parts, most likely because they are transp ...

Differences Between Android and JavaScript: Ensuring Library Validity

Validation in JS is provided by the validator library which can be found at https://www.npmjs.com/package/validator Is there an equivalent library for validation in Android? If so, what is the name of Android's library? ...

No matter how many times I modified the code in the ReactDOM.render() method within my index.js file, the end result remained unchanged

When I ran npx create-react-app my-app, and then proceeded to cd my-app and npm start, a browser opened on localhost:3000. While looking at the index.js file, I noticed that the ReactDOM.render() method included the following code: ReactDOM.render( <Rea ...

How can you position the input cursor at the end of the default text when navigating through fields with the tab key?

I've implemented tab index in the HTML to navigate from one field to another. In the image below, you can see me tabbing from "Revise" to "Link". https://i.stack.imgur.com/vb6L.png However, when I press tab, the default text in the Link field is fu ...

Utilize an Angular HttpInterceptor to invoke a Promise

I have an angular HttpInterceptor and I am in need of invoking an encryption method that is defined as follows: private async encrypt(obj: any): Promise<string> { However, I am unsure of how to handle this within the HttpInterceptor: intercept(req ...

Connect jQuery's resizable controls

Check out this jSFiddle. I am attempting to add event handlers for resizing $('oWrapper_'+num). However, the resizing does not occur. This is because $('#oWrapper_'+num) has not been added to the dom at the time of execution, so the se ...

What is causing the navigation bar object to not adhere to the CSS rules?

My presentation for the MVP is outlined below: .navbar { flex-direction: row; } <!DOCTYPE html> <html lang="en" dir="ltr> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="h ...

Utilizing ngFor to iterate over items within an Observable array serving as unique identifiers

Just starting out with Angular and I'm really impressed with its power so far. I'm using the angularfire2 library to fetch two separate lists from firebase (*.ts): this.list1= this.db.list("list1").valueChanges(); this.list2= this.db.list("list2 ...

Using jQuery to control mouseenter and mouseleave events to block child elements and magnify images

My objective is to create a hover effect for images within specific div elements. The images should enlarge when the user hovers their mouse over the respective div element. I plan to achieve this by adding a child element inside each div element. When the ...

Encountering Typescript issues while trying to access @angular/core packages

Recently, I made an update to my Ionic app from Angular 7 to Angular 8, and an odd error popped up: https://i.sstatic.net/icZOb.png The issue lies in the fact that I am unable to access any of the standard classes stored in the @angular/core module. This ...

Unforeseen truncation issues within a table causing ellipsis to appear unexpectedly

I'm facing an issue with truncating text inside a table, and it's not working as expected. Can someone help me understand what I might be doing wrong? Edit: I need to ensure that the table width remains max-width: 100%; <script src="http ...

Is it feasible to access and modify local files within an Angular project using TypeScript code in the angular component.ts file? If so, how can this be achieved?

My Angular application is built on version 4 or higher. I have a setup in my project where there is a folder containing a txt file and another folder next to it with an angular component.ts file: FolderWithFile -----file.txt ComponentFolder -----person.co ...