Angular Forms

Template Driven Forms

To use template driven forms, make sure that FormsModule is imported from @angular/forms. This can be brought in at the app.module level if needed throughout the application.

<h3>Position</h3>
<form #form="ngForm">
 <input name="title" ngModel>
 <div>
  <button type="submit">Submit</button>
 </div>
</form>

{{ form.value | json }}

In the last line above, the form.value is processed by angular to look at the form and grab the two-binded ngModel value. If we are correlating the specific model properties then we need to use the “[( )]” syntax.

<form #form="ngForm">
 <input name="title" [(ngModel)]="model.title">
 <div>
  <select [(ngModel)]="model.department" name="department">
   <option *ngFor="let d of departments" [value]="d">{{d}}</option>
  </select>
 </div>
 <div>
  <button type="submit">Submit</button>
 </div>
</form>

 

CSS Classes

When a control loses focus angular automatically applies a class to it called “ng-touched”. Also, include a “not(form)” so that the style is only applied to the control and not the whole form. Otherwise the whole form will pickup that styling. We can use a css file to style this.

.ng-touched:not(form) {
 border: 1px solid green;
}
.ng-untouched:not(form) {
 border: px solid blue;
}
.ng-dirty:not(form) {
 border: px solid blue;
}
.ng-pristine:not(form) {
 border: px solid blue;
}
.ng-valid:not(form) {
 border: px solid green;
}
.ng-invalid:not(form) {
 border: px solid blue;
}

Valid and Invalid fields are ruled based on regular expressions or “required” property.

Template reference variables can be used to work with the validation checks in a form. For example:

<form #form="ngForm"> 
 <input #title="ngModel" name="title" [(ngModel)]="model.title">
 <div [hidden]="title.valid || title.pristine">
  Required!
 </div>
 ...
</form>

Note that the above example could be used on the submit button as well. For example

<button type="submit" [disabled]="form.form.invalid">Submit</button>

 

For angular to submit the form by calling a component event, add the “ngSubmit” property on the form field.

<form #form="ngForm" (ngSubmit)="onSubmit(form)">
...

 

There are 3 different ways to create forms in Angular:

  • Template Driven Forms
  • Reactive Forms (easier for unit testing)
  • Dynamic Forms