Angular 8/7 Form Validation with Bootstrap using Template driven Validation

In this tutorial, we will discuss how to implement simple form validation in Angular 8 application using Template-driven validation method.

For form validation tutorial we will use Bootstrap UI library to ease our task. In this form example, we will have Input field, Select box with single and multiple selections, Textarea and a checkbox.

On the form, we will add a template variable to get its reference in our component class using @ViewChild decorator. In component, we will define a method which will be called on clicking submit button on the form.

Let’s get started quickly!

Create an Angular Project

First, create a new Angular 8 project using Ng CLI tool by running following command in terminal:

Add Bootstrap Style

To use bootstrap UI components like form inputs, add bootstrap.css file in the index.html file in the head section:

Import FormModule

We need to import FormModule to use Form control fields and NgModel in app.module.ts file:

Implement Form in Component Template

Now we will add a form in app.component.html file as shown below:

In the form element, we have added template reference variable #MyForm of type ngForm with a (submit) event handler.

Update component class with submit method

Above component is having an interface FormObject defined.

To get form reference in class we used @ViewChild decorator.

Here we also declared a model variable of type formObject and initialized in the class constructor.

In the submitForm method, we are calling markAllAsTouched() method to validate form fields

Error handling in the form

To show red color border on fields, just add following CSS style in styles.css file at the project root.

 

That’s it! here we discussed how to quickly add a Form in Angular project with validations using Template-driven method.

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

avatar
  Subscribe  
Notify of