How to create Angular 9 Form with Template Driven Form using Bootstrap

How to create Angular 9 Form with Template Driven Form using Bootstrap

In this Angular 9 Form tutorial, we are going to learn how to implement simple validation rules with the template-driven approach using Bootstrap forms. Learn how to implement Bootstrap in Angular 9 and create forms with Bootstrap. Learn how to work with the ngModel directive to handle the Angular form data.

To validate the form, we will also look at how to use Bootstrap UI library to facilitate our form validation task. In this Angular form example, we will create a basic form with some Input fields, such as name, email, password and hobbies.

By the end of this tutorial, you will understand following things:

  • How to quickly validate a form with template-driven approach in Angular 9.
  • How to create a form with Bootstrap form template.
  • How to bind ngModel directive with input controls to set the properties on the component.
  • How to submit the form with template driven approach.

Table of Contents

  • Setting Up Angular Project
  • Importing FormsModule
  • Create Form with Bootstrap From Template
  • Implement Template-driven Form in Angular
  • Adding Validation in Template-driven Form
  • Conclusion
Setting Up Angular Project

Run the below command to generate a brand new Angular 9 project using Angular CLI.

ng new angular-template-driven-form

Head over to the Angular form project.

cd angular-template-driven-form

Install Bootstrap in Angular 9

Install Bootstrap UI framework via NPM using following command.

npm install bootstrap

Add the Bootstrap CSS path in styles array inside the angular.json file.

"styles": [
    "src/styles.css",
    "node_modules/bootstrap/dist/css/bootstrap.min.css"
]

Now we have configured Angular and Bootstrap, run the command to open the app in the browser.

ng serve --open
Importing FormsModule

To get started with Form control and NgModel Angular Forms service, we require to import FormsModule in app.module.ts file.

// app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }
Create Form with Bootstrap From Template

Create a simple form in Angular using Bootstrap form component, open the app.component.html file and replace existing code with the following code.

<form novalidate>
  <div class="form-group">
    <label>Name</label>
    <input type="text" class="form-control">
  </div>

  <div class="form-group">
    <label>Email</label>
    <input type="email" class="form-control">
  </div>

  <div class="form-group">
    <label>Password</label>
    <input type="password" class="form-control">
  </div>

  <div class="form-group">
    <label>Hobbies</label>
    <select class="form-control">
      <option value="">Select an option</option>
      <option *ngFor="let hoby of Hobbies" [value]="hoby">
        {{hoby}}
      </option>
    </select>
  </div>

  <div class="form-group">
    <button class="btn btn-danger btn-block">Submit</button>
  </div>
</form>

Also, add the following options array for select drop-down input field in the app.component.ts file.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  Hobbies: string[] = [
    'Acrobatics',
    'Acting',
    'Animation',
    'Astronomy',
    'Baking'
  ];
}
Implement Template-driven Form in Angular

Now we will add the template-driven form using ngModel directive in Angular component. Add the following code in the app.component.html file to initialize the Angular 9 template-driven form.

<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
  <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" class="form-control" [(ngModel)]="model.name" required>
  </div>

  <div class="form-group">
    <label>Email</label>
    <input type="email" class="form-control" name="email" [(ngModel)]="model.email" required>
  </div>

  <div class="form-group">
    <label>Password</label>
    <input type="password" class="form-control" name="password" [(ngModel)]="model.password" required>
  </div>

  <div class="form-group">
    <label>Hobbies</label>
    <select class="form-control" name="hobbies" [(ngModel)]="hobbies">
      <option value="">Select an option</option>
      <option *ngFor="let hoby of Hobbies" [value]="hoby">
        {{hoby}}
      </option>
    </select>
  </div>

  <div class="form-group">
    <button class="btn btn-danger btn-block">Submit</button>
  </div>
</form>

To initiate the template-driven form, add a reference to the NgForm. Declare a template variable with the form by adding the #userForm="ngForm".

To submit the form add onSubmit(userForm) event on the form tag. When a user clicks on the submit button, then the input value will be passed through the onSubmit() method.

We also need to add a name property to the Angular 9 form To register the form control in the form, and it is required to be added.

The ngModel directive formulates a FormControl instance in the Angular form and attaches it with the form control item.

From the hobbies option, a user can select one hoby, add a select field to the form and define the options as Hobbies using *ngFor directive. The ngFor directive will iterate over Hobbies array and create the option tag for every option described in the array.

Open the app.component.ts file and add the following code.

import { Component } from '@angular/core';

export class User {
  public name: string;
  public email: string;
  public password: string;
  public hobbies: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  model = new User();

  Hobbies: string[] = [
    'Acrobatics',
    'Acting',
    'Animation',
    'Astronomy',
    'Baking'
  ];

  constructor() { }

  onSubmit(form) {
    console.log(form.value)
  }
}

Define a property class for the form model; it carries the form field’s value and set the model instance with User Class.

Adding Validation in Template-driven Form

Our Angular form is working correctly, but we have to add validation in our form and convey a strong message to the user if the form fields are invalid.

<form #userForm="ngForm" (ngSubmit)="userForm.form.valid && onSubmit(userForm)">
  <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" class="form-control" [(ngModel)]="model.name" #name="ngModel"
      [ngClass]="{ 'is-invalid': userForm.submitted && name.invalid }" required>
    <div class="invalid-feedback" *ngIf="userForm.submitted && name.invalid">
      <p *ngIf="name.errors.required">Name is required</p>
    </div>
  </div>
</form>

We add the required validation in the name field, to access the form control inside the template. We created the name variable and assigned to “ngModel”.

To add the Bootstrap form validation, we implemented the validation to the class. Class validation applies only when the user submits the form and form is invalid.

To show the error message we used the Angular *ngIf directive and checking the input condition on submission and if the form is invalid.

Same way we applied the form validation in other input fields. Open the app.component.html file and add the following code.

<form #userForm="ngForm" (ngSubmit)="userForm.form.valid && onSubmit(userForm)">
  <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" class="form-control" [(ngModel)]="model.name" #name="ngModel"
      [ngClass]="{ 'is-invalid': userForm.submitted && name.invalid }" required>
    <div class="invalid-feedback" *ngIf="userForm.submitted && name.invalid">
      <p *ngIf="name.errors.required">Name is required</p>
    </div>
  </div>

  <div class="form-group">
    <label>Email</label>
    <input type="email" class="form-control" name="email" [(ngModel)]="model.email" #email="ngModel"
      [ngClass]="{ 'is-invalid': userForm.submitted && email.invalid }" email required>
    <div *ngIf="userForm.submitted && email.invalid" class="invalid-feedback">
      <div *ngIf="email.errors.required">Email is required</div>
      <div *ngIf="email.errors.email">Must be a valid email address</div>
    </div>
  </div>

  <div class="form-group">
    <label>Password</label>
    <input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel"
      [ngClass]="{ 'is-invalid': userForm.submitted && password.invalid }" minlength="8" required>
    <div *ngIf="userForm.submitted && password.invalid" class="invalid-feedback">
      <div *ngIf="password.errors.required">Password is required</div>
      <div *ngIf="password.errors.minlength">Password should be at least 8 characters long</div>
    </div>
  </div>

  <div class="form-group">
    <label>Hobbies</label>
    <select class="form-control" name="hobbies" [(ngModel)]="hobbies">
      <option value="">Select an option</option>
      <option *ngFor="let hoby of Hobbies" [value]="hoby">
        {{hoby}}
      </option>
    </select>
  </div>

  <div class="form-group">
    <button class="btn btn-danger btn-block">Submit</button>
  </div>
</form>

Conclusion

Finally, we have completed the Angular 9 Forms tutorial, and In this tutorial, we learned how to create Angular form with the template-driven approach.

We learnt how to implement Bootstrap in Angular and create forms with Bootstrap.

We looked at how to work with the ngModel directive to handle the Angular form data.

We looked at how to add validation in template-driven forms as well as how to submit a form.

To get the full code of this tutorial visit this GitHub repository.

Thanks a lot for reading this tutorial.

How to integrate Bootstrap 4 with Angular 9?

How to integrate Bootstrap 4 with Angular 9?

In this Angular 9 tutorial, we've seen different ways of integrating Bootstrap 4 in Angular 9 Apps. We will see how to use Bootstrap to style apps built using Angular 9.

In this tutorial, we will see how to use Bootstrap to style apps built using Angular 9.

We'll see how to integrate Angular with Bootstrap, in various ways including using ng-bootstrap and ngx-bootstrap packages.

We'll be using Angular CLI 9 for generating a brand new project.

These are the steps of our tutorial:

  • Step 1 - Installing Angular CLI v9
  • Step 2 - Installing Bootstrap 4 in Your Angular 9 Project
  • Step 3 (Method 1) - Adding Bootstrap 4 to Angular 9 Using angular.json
  • Step 3 (Method 2) - Adding Bootstrap 4 to Angular 9 Using index.html
  • Step 3 (Method 3) - Adding Bootstrap 4 to Angular 9 Using styles.css
  • Alternative Step - Adding Bootstrap 4 Using ng-bootstrap and ngx-bootstrap
What is Bootstrap

Bootstrap is the most popular HTML and CSS framework for building responsive layouts with ease and without having a deep knowledge of CSS (Still custom CSS is required to customize your design ane make it different from the other Bootstrap-styled websites unless you are using a BS theme developed specifically for you).

Bootstrap 4 is the latest version of BS which brings many new and powerful features to the framework most importantly Flexbox which is now the default display system for BS grid layout (one of the most important features of BS).

3+ Ways to Include Bootstrap 4 In Your Angular Project

This can be done in multiple ways:

  • Including the Bootstrap CSS and JavaScript files in the <head> section of the index.html file of your Angular project with a <link> and <script> tags,

  • Importing the Bootstrap CSS file in the global styles.css file of your Angular project with an @import keyword.

  • Adding the Bootstrap CSS and JavaScript files in the styles and scripts arrays of the angular.json file of your project

Step 1 - Installing Angular CLI v9

Let's get started by installing Angular CLI v9 if it is not yet installed on your machine.

Head over to a new command-line interface and run the following command to install the latest version of the Angular CLI:

$ npm install -g @angular/[email protected]

At the time of writing this tutorial, Angular 9 is still in pre-release, so we need to use the next tag to install it. Angular v9.0.0-rc.2 is installed.

Note: This will install the Angular CLI globally on your system so depending on your npm configuration you may need to add sudo (for superuser access) in macOS and Linux or use a command prompt with admin access in Windows.

After the installation, you'll have at your disposal the ng utility. Let's use it to generate a new Angular 9 project.

$ ng new angular-bootstrap-examples

You will be prompted for a couple of questions:

? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? (Use arrow keys)
> CSS
  SCSS   [ https://sass-lang.com/documentation/syntax#scss                ]
  Sass   [ https://sass-lang.com/documentation/syntax#the-indented-syntax ]
  Less   [ http://lesscss.org                                             ]
  Stylus [ http://stylus-lang.com                                         ]

Most importantly, choose CSS as the stylesheet format because we'll use ths CSS version of Bootstrap in our tutorial.

The command will generate the directory structure and necessary files for the project and will install the required dependencies.

Next, navigate inside the root folder of your project

$ cd angular-bootstrap-examples

You can then serve your Angular 9 application using the ng serve command as follows:

$ ng serve

Your app will be served from http://localhost:4200/

Step 2 - Installing Bootstrap 4 in Your Angular 9 Project

In this step, we'll proceed to add Bootstrap 4 to our Angular 9 application.

There are various ways that you can use to install Bootstrap in your project:

  • Installing Bootstrap from npm using the npm install command,
  • Downloading Bootstrap files and adding them to the src/assets folder of your Angular project,
  • Using Bootstrap from a CDN.

Let's proceed with the first method. Go back to your command-line interface and install Bootstrap 4 via npm as follows:

 $ npm install --save bootstrap

This will also add the bootstrap package to package.json.

As the time of writing this tutorial, bootstrap v4.3.1 will be installed.

The Bootstrap 4 assets will be installed in the node_modules/bootstrap folder. You'll need to tell Angular where to look for them.

Next, you also need to install jQuery using the following command:

 $ npm install --save jquery

At the time of this tutorial jquery v3.4.1 will be installed.

Step 3 (Method 1) - Adding Bootstrap 4 to Angular 9 Using angular.json

Open the angular.json file of your project and include:

  • node_modules/bootstrap/dist/css/bootstrap.css in the projects->architect->build->styles array,
  • node_modules/bootstrap/dist/js/bootstrap.js in the projects->architect->build->scripts array,
  • node_modules/bootstrap/dist/js/bootstrap.js in the projects->architect->build->scripts array,

As follows:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1, 
  "newProjectRoot": "projects",
  "projects": {
    "angular-bootstrap-examples": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/angular-bootstrap-examples",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/bootstrap/dist/css/bootstrap.css",
              "src/styles.css"              
            ],
            "scripts": [
              "./node_modules/jquery/dist/jquery.js",
              "./node_modules/bootstrap/dist/js/bootstrap.js"
            ]
          },

Note: You also need to add the jQuery JavaScript library file.

Step 3 (Method 2) - Adding Bootstrap 4 to Angular 9 Using index.html

You can also include Bootstrap files from node_modules/bootstrap using the index.html file.

Open the src/index.html file and add the following:

  • A <link> tag for adding the bootstrap.css file in the <head> section,
  • A <script> tag for adding the jquery.js file before the closing </body> tag,
  • A <script> tag for adding the bootstrap.js file before the </body> tag.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular Bootstrap 4 Examples</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">

</head>
<body>
  <app-root></app-root>
  <script src="../node_modules/jquery/dist/jquery.js"></script>
  <script src="../node_modules/bootstrap/dist/js/bootstrap.js"></script>    
</body>
</html>

Step 3 (Method 3) - Adding Bootstrap 4 to Angular 9 Using styles.css

We can also use the styles.css file to add the CSS file of Bootstrap to our project.

Open the src/styles.css file of your Angular project and import the bootstrap.css file as follows:

@import "~bootstrap/dist/css/bootstrap.css"

This replaces the previous method(s) so you don't need to add the file to the styles array of the angular.json file or to the index.html file.

Note: The JS file(s) can be added using the scripts array or the <script> tag as the previous methods.

Alternative Step - Adding Bootstrap 4 Using ng-bootstrap and ngx-bootstrap

Bootstrap depends on jQuery and Popper.js libraries, and if you don't include them in your project, any Bootstrap components that rely on JavaScript will not work.

Why not include those libs? For Angular it's better to avoid using libraries that make direct manipulation of the DOM (like jQuery) and let Angular handle that.

Now what if you need the complete features of Bootstrap 4 without the JS libraries?

A better way is to use component libraries created for the sake of making Bootstrap work seamlessly with Angular such as ng-bootstrap or ngx-bootstrap

So first you'll need to install the library from npm using the following command:

npm install --save @ng-bootstrap/ng-bootstrap

Once you finish the installation you'll need to import the main module.

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

Next you'll need to add the module you imported in your app root module

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [/*...*/],
  imports: [/*...*/, NgbModule.forRoot()],
  /*...*/
})
export class AppModule {
}

Please note that ng-bootstrap requires the Bootstrap 4 CSS file to be present.

You can add it in the styles array of the angular.json file like that:

"styles": [
  "styles.css",
  "../node_modules/bootstrap/dist/css/bootstrap.css"
],

Now you can use Bootstrap 4 in your Angular application.

You can find all the available components via this link.

You can also use the ngx-bootstrap library

Simply head back to your terminal, make sure you are inside your Angular project then run the following command to install ngx-bootstrap

npm install ngx-bootstrap --save

You also need the Bootstrap 4 CSS files. Add the following line in the <head> of your Angular app which includes Bootstrap from a CDN

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">

You can also install bootstrap from npm and use the previous way to include the CSS file (via the styles array in the angular-cli.json file)

   "styles": [  
   "../node_modules/bootstrap/dist/css/bootstrap.min.css",  
   "styles.css"  
   ],

Next open src/app/app.module.ts and add

import { BsDropdownModule} from 'ngx-bootstrap/dropdown';
import { AlertModule } from 'ngx-bootstrap';

/*...*/

@NgModule({
   /*...*/
   imports: [BsDropdownModule.forRoot(),AlertModule.forRoot(), /*...*/ ],
    /*...*/ 
})

This an example of importing two components BsDropdownModule and AlertModule.

You need to import the module for each component you want to use in the same way.

ngx-bootstrap provides each BS component in each own module so you only import the components you need. In this way your app will be smaller since it bundles only the components you are actually using.

You can find all the available components that you can use from the docs

Adding Bootstrap 4 to Angular 9

Thanks to the new ng add command added on Angular 7+, you have a new simpler and easier way to add Bootstrap without using the npm install command for installing the required dependencies or adding any configurations.

You can simply run the following command to add ng-bootstrap:

$ ng add @ng-bootstrap/schematics

That's it. You now have support for Bootstrap components and styles without any extra configurations. You also don't need jQuery since we are using ng-bootstrap.

Conclusion

In this article, we've seen different ways of including Bootstrap 4 in Angular 9 apps:

  • Using original Bootstrap 4 assets from npm,
  • Using the ng-bootstrap library,
  • And finally using the ngx-bootstrap

The most important difference between ng-bootstrap vs. ngx-bootstrapis that ngx-bootstrap uses separate modules for components to reduce the final app size.

How to add Bootstrap 4 to your Angular 8 Project?

How to add Bootstrap 4 to your Angular 8 Project?

In this Angular 8 tutorial, I will give you example of how to add Bootstrap 4 in Angular 8 Project. As we know Bootstrap is the world’s most popular framework for building responsive, and mobile-first sites. Bootstrap provide several class for making responsive website for your mobile.

Here, I will give you example of how to add Bootstrap 4 in Angular 8 project. You can easily install Bootstrap in Aangular 8. I will also give you example of how to use bootstrap in Angular 8. You can easily understand Angular 8 install Bootstrap 4 and use it.

As we know Bootstrap is the world’s most popular framework for building responsive, and mobile-first sites. bootstrap provide several class for making responsive website for your mobile. So if you want to use bootstrap with angular 8 than I will help you very simple way.

I have a two install bootstrap and use it with your Angular 8 project. I will give you both way example bellow.

You can easily create your angular app using bellow command:

ng new my-new-app

Example 1:

In this solution, you need to just install bootstrap on your angular 8 and import css file to style.css file. this is only for css importing. so you can run command bellow:

npm install bootstrap --save

Ok, now you need to import your bootstrap css on style.css file as like bellow:

src/style.css

@import "~bootstrap/dist/css/bootstrap.css";

Now you can use bootstrap class in your angular 8 app. It will works.

Example 2:

In this solution, we will also install bootstrap with jquery and popper js. so that way you can also import bootstrap css and bootstrap js function. So i think this will be best solution for you i think.

let's run following commands:

npm install bootstrap --save
npm install jquery --save
npm install popper.js --save

Now after successfully run above command. let's import it in angular.json file.

angular.json

{

  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",

  "version": 1,

  "newProjectRoot": "projects",

  "projects": {

    "my-app": {

      "projectType": "application",

      "schematics": {},

      "root": "",

      "sourceRoot": "src",

      "prefix": "app",

      "architect": {

        "build": {

          "builder": "@angular-devkit/build-angular:browser",

          "options": {

            "outputPath": "dist/my-app",

            "index": "src/index.html",

            "main": "src/main.ts",

            "polyfills": "src/polyfills.ts",

            "tsConfig": "tsconfig.app.json",

            "aot": false,

            "assets": [

              "src/favicon.ico",

              "src/assets"

            ],

            "styles": [

              "node_modules/bootstrap/dist/css/bootstrap.min.css",

              "src/styles.css"

            ],

            "scripts": [

                "node_modules/jquery/dist/jquery.min.js",

                "node_modules/bootstrap/dist/js/bootstrap.min.js"

            ]

          },

          .....

Now you can use bootstrap css and js both.

Now you can check your angular 8 project.

I hope it can help you...

18 Angular UI Element Directives For Bootstrap

18 Angular UI Element Directives For Bootstrap

It can be attributes, classes or elements. Using elements allows us to create modular UI components for web apps. So in this post we`ve collected some useful Bootstrap ui components remade as AngularJS directives.

Directives are an awesome tool that essentially lets you create new HTML tags, or supercharge existing tags with attributes. Directives allow you to create custom HTML components. It can be attributes, classes or elements. Using elements allows us to create modular UI components for web apps. So in this post we`ve collected some useful Bootstrap ui components remade as AngularJS directives.

Lightbox

When the lightbox is opened, navigating to the previous/next image can be achieved by clicking buttons above the image, clicking the left/right arrow keys, or swiping to the left/right (optional with ngTouch). The escape key for closing the modal is automatically binded by AngularUI Bootstrap.

Tree directive

An AngularJS directive that creates a Tree based on a Bootstrap “nav” list. The style is completely Bootstrap because the tree is actually just a Bootstrap “nav” list, with a few changes: Indentation is added, expand/collapse icons are added, and Angular CSS animations are used during expand/collapse.

nya-bootstrap-select

An AngularJS select replacement which build select like dropdown component with collection and ng-model support

Dialog service

A complete AngularJS service with controllers and templates for generating application modals and dialogs for use with Angular-UI-Bootstrap and Twitter Bootstrap

contextMenu

AngularJS UI Bootstrap Module for adding context menus to elements.

Iconpicker

A Bootstrap 3 Icon Picker implemented in AngularJS.

Confirm

A simple angular directive to display a bootstrap styled confirmation popover when an element is clicked.

AutoFields

Avoid bloating your templates with repetitive form html. Instead, just specify a schema for the form and the model you want to bind it to and you’re done!

Off canvas

Off canvas side menu for use with ui-bootstrap 0.14+. Extends ui-bootstrap’s $uibModal provider.

Tab scroll

A scrollable tab plugin compatible with angular-ui bootstrap tabs

Chat

Simple AngularJS Chat Directive with Bootstrap.

Notification

Angular.js service providing simple notifications using Bootstrap 3 styles with css transitions for animations.

Placeholders

Angular directive for enhanced placeholders that easily integrate with Bootstrap form fields.

Button

Angular/Bootstrap animated submit button directive.

Datetime picker

AngularJs directive to use a date and/or time picker as a dropdown from an input.

Formly

This is a template for angular-formly which adds templates with classes specific to bootstrap. Each field is wrapped in a div. This library is not standalone and requires angular-formly to be present and loaded.