Jaimin Bhavsar

Jaimin Bhavsar

1576297117

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

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.

#Angular #Bootstrap #WebDev #JavaScript

What is GEEK

Buddha Community

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

Jaimin Bhavsar

1576297117

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

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.

#Angular #Bootstrap #WebDev #JavaScript

Turner  Crona

Turner Crona

1595950620

Angular simple dynamic template-driven form for beginners

Template driven forms are model driven forms driven by directives in a template. Template driven forms are approached by angular JS users but sometimes template driven forms will be used for complex systems. For instance, if you want to dynamically set to validate a particular form filed you can use template driven forms. In the template driven forms uses two way data binding in terms of it uses ngModel despite formControl and fromGroups.

Form structure

I am going to create a simple form that is able to create new form fields. The number of form-fields depends on the user. It can be changed at run time.

However, each form entry requires a name like formControlName in reactive forms and the state of the form as a whole that is a collection of individual form fields. Each form filed is assigned a unique id property. Therefore, template driven form controls need to be uniquely named. We can generate form fields using a unique control name. In this dynamic form, it has been used the current timestamp as a unique id or you can create a method to get random numbers to assign for this unique id. So it can get through with parent NgForm.

First, import formsModule to main module ex:- app.module.ts then create an interface to describe an object. You have to set some properties you want to this interface.

<form #parentForm="ngForm" (submit)="submitParentForm(parentForm)">
	    <ng-template ngFor let-form [ngForOf]="mainForm.formFields" let-index="index" let-isLast="last">
	        <input
	            type="form.formField1.type"
	            name="formFirld1_{{ form.id }}"
	            [(ngModel)]="form.formField1.value"
	            placeholder="form.formField1.placeholder"
	            required
	        />
	        <div *ngIf="parentForm.submitted && !form.formField1.value">Form field 1 is required</div>
	        <input
	            type="form.formField2.type"
	            name="formFirld2_{{ form.id }}"
	            [(ngModel)]="form.formField2.value"
	            placeholder="form.formField2.placeholder"
	            required
	        />
	         <div *ngIf="parentForm.submitted && !form.formField2.value">Form field 2 is required</div>
	        <button (click)="removeForm(index)">Remove form</button>
	    </ng-template>
	    <button type="submit">Submit</button>
	    <button type="button" (click)="parentForm.reset()">
	        Reset
	    </button>
	</form>
	<button (click)="addForm()" [disabled]="(!parentForm.form.valid)">Add new form</button>

#dynamic-form #angular-for-beginners #template-driven-form #angular

Hal  Sauer

Hal Sauer

1591066502

How to Make Simple Sidebar Template with Bootstrap 4 and Angular 9?

In this post, I will tell you, How to make simple sidebar template with Bootstrap 4 and Angular 9?

In this, you can see bootstrap toggle sidebar navigation menu. During click on Toggle menu, sidebar navigation will show and hide.

#angular 8 #angular 9 #angular7 #bootstrap 4 #bootstrap templates

Clara  Gutmann

Clara Gutmann

1599459851

Angular Sass: How To Use Sass In Angular 9 Tutorial

Angular supports Sass, CSS, and Less to style global application styles as well as component styles. Angular components styles have an effective CSS encapsulation mechanism that assures any component CSS is local to the component and does not globally alter any styles.

Angular Sass Example

Why use Angular Sass? Well!! Sass (Syntactically Awesome Style Sheets) is an extension of CSS that allows you to use things like variables, nested rules, inline imports, and more. It also supports you to keep things organized and enables you to create style sheets faster.

In short,  Sass is a CSS preprocessor, which combines unique features such as variables, nested rules, and mixins (sometimes referred to as syntactic sugar) into regular CSS. The main object of Sass is to make the CSS coding process more comfortable and more efficient.

Sass is compatible with all versions of CSS. When working with the Angular CLI, the default stylesheets have the .css extension. We are using Angular CLI 8. So, if you have not used previously, then please upgrade your  CLI version. We will use the Bootstrap 4 Framework for this demo and see how we can configure the Sass in our Angular 9 application.

#angular #angular 9 #angular cli #css #angular sass

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli