Angular, Forms

Template Driven Forms

Spread the love

What is angular template driven form?

Template Driven Form is written inside HTML user interface. This is one of the simplest form creation methods in Angular 2+. No code is involved in .ts component file.

Template-driven forms is use two-way binding data to update the data model in an object as changes are made to the template and vice versa.

Enable template driven FormsModule

import the FormsModule into AppModule or your custom module if your component under the custom module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { TemplateDrivenFormComponent } from './hero-form/hero-form.component';

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

Follow others helpful articles

ngModel

We need ngModel in form submission, and input should also be mentioned:

<input type="text" ngModel name="firstName">

There are cases where we need to transfer the event listener to the input field, or to transfer the input value to our item, we need to assign a statistical variable to the input to do so.

<input type="text" ngModel 
       name="name" 
<input type="text" ngModel 
       name="firstName" 
       #firstName="ngModel"
       (change)="doSomething(firstName)"
>

The ngModel is an example of a FormControl with many controls including dirty, invalid, errors, pristine, touched, untouched, value etc. The FormControl section is used to track state changes in our input.

ngForm:

NgForm is an example of FormGroup. FormGroup represents the FormControl team, each form being a FormGroup because it will have at least one FormControl that gives us access to (by Submit) which can be linked to a particular method on our part.

<form #userForm="ngForm" (ngSubmit)="submitUserForm(userForm)">
<form #f="ngForm" (ngSubmit)="submit(f)">
  <input type="text" ngModel 
         name="firstName" 
         #firstName="ngModel"
         (change)="doSomething(firstName)"
  >
</form>

FormGroup also has many features such as FormControl such as dirty, errors, invalid, parent, etc.

ngModelGroup:

Sometimes, when a complex form is created. The need may arise when we need to make something parental in another input, so that we can access that input under the parent, which is why the need for ngModelGroup. We can access the first name and last name under a person object.

<form #f="ngForm" (ngSubmit)="submit(f)">
  <div ngModelGroup="person">
     <input type="text" ngModel 
           name="firstName" 
           #firstName="ngModel"
           (change)="doSomething(firstName)"
     >
     <input type="text" ngModel 
           name="lastName" 
           #lastName="ngModel"
           (change)="doAnotherthing(lastName)"
     >
  </div>
</form>

Dealing with checkboxes?

To deal with the checkboxes, we need to use the ngModel and name the selection as we did before.
Do you like this article?

<label>
  <input type="checkbox" ngModel name="like"> Like this article?
</label>


Since the checkbox does not have a value asset, when you click on the checkbox, the true value is given the same but the false value is used when you delete the dial.

Dealing with Radio Buttons?

To deal with the radio buttons, we need to use the ngModel and name the option as we did before.

<label>
  <input type="radio" ngModel name="clap" value="2"> 2 claps?
</label>
<label>
  <input type="radio" ngModel name="clap" value="3"> 3 claps?
</label>

Dealing With Select Options?

To deal with selection options, we need to use ngModel and name the option as we did before. We then use * ngFor to open options when it appears in an object / back

//assuming we have an array of objects like below in our component
export class MyFormComponent {
  myOptions = [
    {id: 1, name: "abel"},
    {id: 2, name: "agoi"},
    {id: 3, name: "adeyemi"},
  ];
}
//below is how we will use the above in our template
//my-form-template.html
<select ngModel name="person">
  <option *ngFor="let myOption of myOptions" [value]="myOption.id"> 
      {{ myOption.name }}
  </option>
</select>
//not coming from database
<select ngModel name="person">
  <option value="1">abel</option>
  <option value="2">agoi</option>
  <option value="3">adeyemi</option>
</select>
<label *ngFor="let myOption of myOptions">
  <input type="radio" ngModel name="clap" [value]="myOption.id"> 
  {{ myOption.name }}
</label>

ngForm Validation

We will look to add html verification and highlight the appropriate errors when authentication fails. The most important things we will link to are the legal status of the form control or our form group.

required: use to force the user that input must be completed.

<input type="text" ngModel name="firstName" required>

We may use FormControl’s official property to display the correct message if verification fails, and we need to make sure the form has been touched before concluding that the verification failed, which is why you need to touch or contact

<input type="text" ngModel name="firstName" #firstName="ngModel" required>
<div *ngIf="firstName.touch && ! firstName.valid">
  Firstname is required
</div>

Error message The first name required will only show if the input is touched and incomplete. We should always provide flexible form controls # firstName = “by Model” in order to display the verification message.


Maxlength, Minlength and Pattern: Maxlength is used to force a large number of characters into inputs that you can accept. Minlength is used to eliminate the minimum number of characters an input can accept. Pattern Attribution is widely used for general form validation confirmation. When we have more confirmation of the input, we can look at each of the errors below:

<input type="text" ngModel
       name="firstName" #firstName="ngModel" 
       minlength="3"
       maxlength="10"
       required
>
<div *ngIf="firstName.touch && ! firstName.valid">
  <div *ngIf="firstName.errors.required">
    Firstname is required
  </div
  <div *ngIf="firstName.errors.minlength">
    Firstname minimum length is
    {{ firstName.errors.minlength.requiredLength }}
  </div>
  <div *ngIf="firstName.errors.maxlength">
    Firstname maximum length is
    {{ firstName.errors.maxlength.requiredLength }}
  </div>
</div>

invalid, ng dirty, ng-touch: angular automatically attach these classes to our input when input is invalid, dirty and touched. ng-invalid is added when verification fails or requirement is not met, ng-invalid is added when the user participates with the installation, ng-touch is installed when the user loses focus. We can increase the use of our form by using these powerful features to style our form as below:

<input type="text" ngModel
       name="firstName" #firstName="ngModel" 
       minlength="3"
       maxlength="10"
       required
       class="form-control"
>

Assuming we have class .form-control added to our input form, good angular add will add .ng-touch, .ng-dirty, .ng-touch where appropriate, we can add those classes to our style to enhance our form communication. Add below code in css file.

.form-control.ng-touched.ng-invalid {
border: 2px solid red;
}

Disables the submit button: we can disable the submit button form or just any easily inserted angular. I will disable the submit button for us if all form is invalid.

<form #f="ngForm" (ngSubmit)="submit(f)">
  
  <input type="text" ngModel 
         name="firstName" 
         #firstName="ngModel"
         (change)="doSomething(firstName)"
  >
  <input type="text" ngModel 
         name="lastName" 
         #lastName="ngModel"
         (change)="doAnotherthing(lastName)"
  >
  <button [disabled]="!f.valid">Submit</button>
</form>

Respond to the [disabled] on !F.valid, #f is the form reference given to the form.
The authentication made here is just a built-in html 5 authentication, we can customize our own authentication. There is also another method of constructing angular forms known as functional forms. We will write about that soon.

References

Thank you! Like our Facebook page for more updates.


Spread the love
Tagged , , , , , , , , , , ,

About Chandra

Technology lover. Professionally Software Developer and write some Technical Blog to help newcomer.
View all posts by Chandra →